glibc中_exit()函数实现及跨平台调用逻辑的技术问询
Great questions about glibc's _exit() implementation—let's break them down clearly:
1. What's the specific implementation of _exit() in glibc?
Unlike the standard exit() function (which handles user-space cleanup like flushing stdio buffers, running atexit() handlers, and closing streams), _exit() is a minimal, low-level wrapper that skips all those user-space steps. Its core job is to immediately tell the operating system to terminate the process and return an exit status.
On Unix-like systems, _exit() directly triggers the kernel's exit system call. It passes the exit status to the kernel, which then takes over: reclaims the process's memory, closes any open file descriptors (that aren't marked FD_CLOEXEC), sends a SIGCHLD signal to the parent process, and cleans up other kernel-side resources.
The implementation is lean—no extra user-space logic, just the bare minimum to transition to kernel mode and invoke the system call.
2. Where can I find the _exit() function body in the glibc source code?
Glibc is highly modular and platform-specific, so the exact location depends on your target OS and architecture:
- For Unix-like systems (e.g., x86_64 Linux): Check the
sysdeps/unix/sysv/linux/x86_64/directory—you'll likely find a_exit.c(or sometimes an assembly file, since system calls often use architecture-specific register setup) that contains the implementation. - There's also a generic wrapper in
stdlib/_exit.c, but the actual system call trigger is delegated to platform-specific code in thesysdepshierarchy. - To locate it quickly, you can run a search across the glibc source tree for
_exitfunction definitions—look for files named_exit.cor assembly files (.S) that handle the system call transition.
3. Does glibc's _exit() call different OS-specific functions (like Unix's exit syscall vs. Windows' ExitProcess())?
Absolutely—this is part of glibc's role as a cross-platform C standard library.
- On Unix-like systems,
_exit()maps directly to the kernel'sexitsystem call (the exact system call number varies by OS/architecture, but glibc handles that translation). - On Windows, since there's no equivalent Unix-style
exitsystem call, glibc's_exit()wraps the Windows API functionExitProcess(), which serves the same purpose of terminating the process immediately and returning an exit code to the OS.
This platform-specific adaptation lets C programmers use _exit() consistently across systems, while glibc handles the low-level OS differences under the hood.
内容的提问来源于stack exchange,提问作者Darshan L

