Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...