Linux下exit()函数的status参数传递给父进程还是操作系统内核?
exit() Status Parameter Flow in Linux Great question—this is a common point of confusion because there are a few layers involved here, so let’s unpack it step by step:
1. What exit() actually does with the status parameter
First, remember that exit() is a C standard library function, not a system call directly. When you call exit(int status), it first runs all user-space cleanup tasks:
- Flushes all open standard I/O streams
- Calls functions registered with
atexit()oron_exit() - Closes open file descriptors (that aren't marked
FD_CLOEXEC) - And other cleanup defined by the C standard
Once that's done, exit() invokes the kernel's _exit() system call, passing the low 8 bits of your status parameter directly to the kernel. At this point, the status is handed off to the kernel—not the parent process.
2. How the parent process (like your Shell) gets the status
The kernel doesn't discard the status. It stores it alongside the terminated process, marking the process as a "zombie" (state Z in ps output) until the parent process comes to collect it.
For example, when you run a program in your Shell:
- The Shell forks a child process to run your program
- When the child calls
exit(), the kernel holds onto its exit status - The Shell then calls
wait()orwaitpid()(system calls) to retrieve that status from the kernel - That's why you can run
echo $?right after a command to see the exit code—$?is the value the Shell fetched from the kernel.
3. Reconciling with APUE's description
APUE's statement that exit() "returns to the kernel after performing specific cleanup" is exactly right. The library function exit() wraps the kernel's _exit() system call; the status is delivered to the kernel first, and the parent process gets it indirectly from the kernel, not directly from the child process.
To sum up:
- The
statusparameter fromexit()is directly passed to the Linux kernel (via the_exit()system call). - The parent process (like your Shell) retrieves the status from the kernel using
wait()/waitpid(), rather than receiving it directly from the child.
内容的提问来源于stack exchange,提问作者Tim

