Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait()/waitpid() returns 1, not pid of child, how to fix that?

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!

like image 303
Some Noob Student Avatar asked Dec 11 '10 04:12

Some Noob Student


1 Answers

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 ) { ...
like image 167
Nikolai Fetissov Avatar answered Oct 12 '22 09:10

Nikolai Fetissov