0

everyone. I've got a problem that is making me very confused. I'm just trying to print out the status received from a terminated process but it isn't working the way I thought it would. Here is the code.

int main(int argc, char *argv[])
{
  printf("this process (%d)\n",(int)(getpid()));
  int *status;
  pid_t pid;
  Signal(SIGINT, handler1);

  if ((pid = fork())==0){
    while(1)
      ;
  }
  kill(pid,SIGINT);
  while(pid>0){
    pid = waitpid(pid,status,0);
    printf("status: %d\n", WEXITSTATUS(status));
    printf("waitpid return: %d\n",(int)pid);
  }
  return 0;
} 

void handler1(int sig){
  printf("process (%d) has received a sigint\n",(int)(getpid()));
  exit('d');
}

it has output

this process (8811)
process (8812) has received a sigint
status: 0
waitpid return: 8812
status: 0
waitpid return: -1

when I use WIFEXITED(status) it returns true. So shouldn't WEXITSTATUS return what I passed through exit and not 0?

I did not include the Signal function here.

Paul Myers
  • 41
  • 1
  • 1
  • 6
  • when I use WIFSIGNALED(status) it outputs status: 0. Even if I get rid of the signal handler and just send it kill(pid,SIGINT), it returns 0. – Paul Myers Dec 08 '15 at 03:00

1 Answers1

0

Here's your problem

int *status;
...
pid = waitpid(pid,status,0);
printf("status: %d\n", WEXITSTATUS(status));

You're not allocating space for the status. You're just declaring a pointer (which is probably initialized to 0, or NULL when we're talking pointers), and then passing it to waitpid (which, if it receives a NULL for the status, ignores it, which prevents a segfault), and then you're passing that NULL pointer to the EXITSTATUS() macro which wants an int (but it treats it as a zero, anyway). And you get "status: 0".

What you want to do is declare your status as a regular int, and then pass its pointer to waitpid():

int status;
...
pid = waitpid(pid,&status,0);
printf("status: %d\n", WEXITSTATUS(status));

This will print out "status: 100" like you're looking for.

Jemenake
  • 2,092
  • 1
  • 20
  • 16