Why does wait() set status to 255 instead of the -1 exit status of the forked process?

user191776 picture user191776 · Sep 7, 2010 · Viewed 23.2k times · Source

I'm trying to return an integer value from a child process.

However, if I use exit(1) I get 256 as the output from wait(). Using exit(-1) gives 65280.

Is there a way I can get the actual int value that I send from the child process?

if(!(pid=fork()))
{
    exit(1);
}
waitpid(pid,&status,0);
printf("%d",status);

Edit: Using exit(-1) (which is what I actually want) I am getting 255 as the output for WEXITSTATUS(status). Is it supposed to be unsigned?

Answer

Darron picture Darron · Sep 7, 2010

Have you tried "man waitpid"?

The value returned from the waitpid() call is an encoding of the exit value. There are a set of macros that will provide the original exit value. Or you can try right shifting the value by 8 bits, if you don't care about portability.

The portable version of your code would be:

if(!(pid=fork()))
{
    exit(1);
}
waitpid(pid,&status,0);
if (WIFEXITED(status)) {
    printf("%d", WEXITSTATUS(status));
}