You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于fork、wait、WEXITSTATUS的代码分析及wait返回值疑问

Understanding the Wait Status Value in Your C Code

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:

  1. Parent process sets value = 3, then calls fork().
  2. Child process runs the else block: calls exit(3) to terminate with exit code 3.
  3. Parent process runs the if block: calls wait(&value), which sets value to the compound status word 768 (3*256).
  4. Parent process uses WEXITSTATUS(value) to extract the exit code, so value becomes 3 again.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:28:58