What happens to the resources that aren't cleaned up when you use _exit in UNIX?
I'v开发者_如何学Ce read that you can call either exit
or _exit
when you wish to terminate a process in UNIX, and also that exit frees resources (the style used when we return from main) where _exit immediately terminates without cleanup.
What is the impact of closing a program with _exit with regard to the operating environment, and why would you want to use it?
There is no difference in resources freed when exiting with _exit
versus exit
unless you have installed atexit
handlers. Named shared memory objects, SysV IPC resources, files in the filesystem, etc. will not be destroyed on either type of exit; memory allocated to the process (in fact, its whole virtual memory space), file descriptors, etc. will be destroyed either way. For details read the documentation in POSIX:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
http://pubs.opengroup.org/onlinepubs/9699919799/functions/exit.html
Usually the only important difference is that stdio FILE objects might not be flushed (some writes may be lost) if you use _exit
.
From the man page:
exit
:
The exit() function first calls all functions registered by atexit(3C), in the reverse order of their registration, except that a function is called after any previously registered functions that had already been called at the time it was registered.
_exit
:
The _Exit() and _exit() functions are functionally equivalent. They do not call functions registered with atexit(), do not call any registered signal handlers, and do not flush open streams.
In other words exit
and _exit
still do resource (such as file handles and allocated heap memory) reclamation if the OS does so, but user-defined things such as static destructors won't be called, and files won't be flushed in the _exit
case.
Your program is automatically equipped with some default atexit()
handlers. Call exit()
and
- Streams for files and pipes that are still open will be flushed and closed.
- Global data will be destructed.
Call _exit()
and
- Streams for files and pipes that are still open will not be flushed. You most likely will lose data in output files.
- Global data will not be destructed.
In both cases,
- Any memory you have allocated is recovered.
- Exited child processes that you did not reap will still be in the process table (However, zombies don't appear to be the big problem they were long ago.)
- Still-running child processes become orphans and are adopted in the
init
process.
精彩评论