5

this is a follow up to How to squeeze in additional parameters to a reaper function when a parent is signalled to kill a child (c)?

In my reaper(), I try to obtain the child's pid the parent is about to finish (non-brutal word here). but wait() does not return the pid of the child; instead, it returns 1. I can't find a doc for return value of 1 anywhere. Any heads up?

void    reaper(int sig)
{
    int status, killedpid;

    while(killedpid = (/*waitpid(-1, &status, WNOHANG)*/wait(&status)) >= 0)
    {
        printf("reaper %d killed %d\n", getpid(), killedpid);
    }
}

My results:

reaper 5933 killed 1 //actual child pid is 5936

Thank you in advance!

Community
  • 1
  • 1
Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
  • Oh, I say go ahead with the terminology. That's part of the fun of *nix. "The child died, and the parent reaped the zombie process." – Thanatos Dec 11 '10 at 07:47

1 Answers1

15

This is the classic assignment in conditional error - the expression is evaluated as following (because comparison has higher precedence then assignment):

if ( killedpid = ( wait( &status ) >= 0 )) { ...

The killedpid will get a value of TRUE, which is 1 in C. To get around this use parenthesis and compile with high warning levels like -Wall -pedantic:

if (( killedpid = wait( ... )) >= 0 ) { ...
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • The same applies to PHP. I used `pcntl_waitpid()` and had the same error causing the return value to always appear as `1`. – Marki555 Feb 20 '18 at 21:36