关于fork、wait、WEXITSTATUS的代码分析及wait返回值疑问
Hey there! Let's clear up that confusion with your wait() call returning 3*256 instead of the expected 3. It all comes down to how the wait() function stores exit status information.
First, How wait() Works
The integer pointer you pass to wait() doesn't get set directly to the child's exit code. Instead, it stores a compound status word that packs multiple pieces of info:
- Whether the child exited normally or was terminated by a signal
- If it exited normally, the actual exit code is stored in the high 8 bits of this status word
- If it was killed by a signal, the signal number is in the low bits
When your child process calls exit(3), it exits normally with code 3. The status word created for this is 3 << 8 (shifting 3 left by 8 bits), which equals 3*256 = 768—that's exactly what you're seeing after the wait(&value) line.
What WEXITSTATUS() Does
The WEXITSTATUS() macro exists specifically to extract the actual exit code from this status word. It takes the status value, shifts it right by 8 bits, and masks it with 0xFF to get the original exit code. So when you run:
value = WEXITSTATUS(value);
That 768 gets converted back to 3. Then value++ makes it 4, which is what your printf will output.
Step-by-Step Breakdown of Your Code
Let's walk through the execution flow to make it crystal clear:
- Parent process sets
value = 3, then callsfork(). - Child process runs the
elseblock: callsexit(3)to terminate with exit code 3. - Parent process runs the
ifblock: callswait(&value), which setsvalueto the compound status word768(3*256). - Parent process uses
WEXITSTATUS(value)to extract the exit code, sovaluebecomes 3 again. value++increments it to 4,printf("%d", value)outputs 4, and the parent returns 4.
This is all standard behavior for wait() and the status macros—you weren't doing anything wrong, just missing that extra layer of status parsing!
内容的提问来源于stack exchange,提问作者mathkid

