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
1.4k views
in Technique[技术] by (71.8m points)

c - I used wait(&status) and the value of status is 256, why?

I have this line in my code :

t = wait(&status); 

When the child process works, the value of status is 0, well.

But why does it return 256 when it doesn't work? And why changing the value of the argument given to exit in the child process when there is an error doesn't change anything (exit(2) instead of exit(1) for example)?

Thank you

Edit : I'm on linux, and I compiled with GCC.

I defined status like this

int status;
t = wait(&status); 
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Given code like this...

int main(int argc, char **argv) {
    pid_t pid;
    int res;

    pid = fork();
    if (pid == 0) {
        printf("child
");
        exit(1);
    }

    pid = wait(&res);
    printf("raw res=%d
", res);

    return 0;
}

...the value of res will be 256. This is because the return value from wait encodes both the exit status of the process as well as the reason the process exited. In general, you should not attempt to interpret non-zero return values from wait directly; you should use of the WIF... macros. For example, to see if a process exited normally:

 WIFEXITED(status)
         True if the process terminated normally by a call to _exit(2) or
         exit(3).

And then to get the exit status:

 WEXITSTATUS(status)
         If WIFEXITED(status) is true, evaluates to the low-order 8 bits
         of the argument passed to _exit(2) or exit(3) by the child.

For example:

int main(int argc, char **argv) {
    pid_t pid;
    int res;

    pid = fork();
    if (pid == 0) {
        printf("child
");
        exit(1);
    }

    pid = wait(&res);
    printf("raw res=%d
", res);

    if (WIFEXITED(res))
        printf("exit status = %d
", WEXITSTATUS(res));
    return 0;
}

You can read more details in the wait(2) man page.


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

...