The difference between exit and _exit in Linux

Source: Internet
Author: User
Tags function definition glob signal handler terminates

The difference between the Exit,_exit

-The difference between exit () and _exit () function (Linux system) 2012-03-20 15:19:53

Category: LINUX

Note: exit () is exit, The passed-in parameter is the status code when the program exits, 0 -1 1 c exit_success and exit_failure Two macros, with exit (exit_success); readability is a little better.

As a system call,_exit and exit are twins, and we can Find the answer from the Linux source:

#define __NR__EXIT __nr_exit/* Excerpt from file include/asm-i386/unistd.h line No. 334 */

"__nr_" is the prefix for each system call in the Linux source, note that there are 2 underscores before the first exit, and only 1 underline before the second exit. At this point, a person who understands C and has a clear mind will say that there is no difference between _exit and exit, but we also want to talk about the difference between the two, which is mainly reflected in their definition of the function library. The prototypes of _exit in the Linux libraries are:

#i nclude<unistd.h> void _exit (int status);

exit () 1. call atexit () registered function (Exit Function) ; Press atexit For example Save the program state information to a file Unlock the lock on the shared database, etc.

2.cleanup (); closes all open streams, which will cause all buffered output to be written, deleting all temporary files created with the Tmpfile function .

3. finally call the _exit () function to terminate the process.

_exit do 3 man 1 any open file descriptors belonging to the process are closed 2 any children  of the process are inherited by process 1, init 3, the process ' s parent is sent a  Sigchld signal

Exit calls _exit after the cleanup is done to terminate the process.

In addition, another explanation:

Simply put, the exit function terminates the calling process. Before exiting the program, all files are closed, the buffered output refreshes the definition, and all flushed "exit functions" (defined by atexit) are called.

_exit: This function is defined by POSIX and does not run exit handler and signal handler and does not flush the standard I/O stream in Unix systems.

Simply put, _exit terminates the calling process, but does not close the file, does not clear the output cache, and does not call the egress function.

Common:

Regardless of how the process terminates, the kernel closes all file descriptors opened by the process, releasing the memory! used by the process

A more detailed description:

Calling exit () the exit () function causes normal program termination.

The exit ()  function performs the following functions:1. all functions  registered by the standard c atexit ()  function are called  In the reverse order of registration. if any of these functions  calls exit (),  the results are not portable. 2. all open output streams are flushed  (data written out)   And the streams are closed. 3. all files created by tmpfile ()  are deleted. 4. the _exit ()  function is called. Calling _exit () the _exit ()  function performs operating system-specific  Program termination functions. these include:1. all open file descriptors and directory streams  Are closed. 2. if the parent process is executing a wait ()  or waitpid (), the  Parent wakes up and status is made available. 3. if the parent is not executing a wait ()  or waitpid (),  the status is saved for return to the parent on a  Subsequent wait ()  or waitpid (). 4. children of the terminated process are assigned a new  Parent process id. note: the Termination of a parent does not  directly terminate its children. 5. if the implementation supports the sigchld signal, a sigchld  is sent to the parent. 6. several job control signals are sent.

Why use the _exit function in a fork Sub-process branch without using the exit function? ' exit () ' differs from ' _exit ' () ' in the use of ' fork' () ', especially ' vfork () ' become very prominent.

' Exit () 'with the' _exit () 'The basic difference is that the previous invocation implements and invokes the user state structure in the library.(User-mode constructs)about the cleanup work(clean-up), and calls the user-defined cleanup program(Custom Cleaner is defined by theatexit function definition, can be defined multiple times and executed in reverse order), corresponds to,_exitthe function only enforces kernel cleanup for the process. In the' fork () 'created sub-process branch, normally used' exit () 'is incorrect because using it will result in standard input and output(Stdio:standard Input Output)of theThe buffer was emptied two times, and the temporary file was unexpectedly deleted (temporary files are created bytmpfileThe function is created in the system temp directory, and the file name is randomly generated by the system). In theC + +the situation in the program will be worse becauseStatic targets (static objects)the destructor(destructors)can be executed incorrectly. (There are some special cases, such asDaemons, their parent processes need to call the' _exit () 'rather than sub-processes;The basic rule that applies to most situations is that' exit () 'at every entry'MainfunctionCalled only once.)In the' vfork () 'in the sub-process branch that you created,' exit () 'use will be more dangerous because it will affect the state of the parent process.

#include <sys/types.h>; #include <stdio.h> int glob = 6;  /* External variable in initialized data */int main (void) {int var;/* Automatic variable on the stack */pid_t pid; var = 88; printf ("Before vfork\n";/* We don't flush stdio */if (PID = Vfork ()) < 0) printf ("Vfork error\n"; else if (PID = = 0 {/* child/glob++;/* Modify parent ' s variables */var++; exit (0);/* Children terminates *///Sub-process preferably with_exit (0)more secure. }/* Parent */printf ("pid =%d, Glob =%d, var =%d\n", Getpid (), Glob, Var); Exit (0); Running on a Linux system, the parent processprintfthe content output:pid = 29650, Glob = 7, var =

Child processes are shutting down their own, although they share standard input, standard output, standard error, etc. " Open File ", the child process exit , but also decrements a reference count , it is not possible to close the parent process, so the parent process still has output.

On other Unix systems, however, the parent process might not have output because the child process called e x i t, and it flushed off all standard I/O streams, including standard output. Although this is performed by a child process, it is in the address space of the parent process, so all the affected standard I/O FILE objects are in the parent process. When the parent process calls p r i n t f , the standard output is closed, and p r i n t f returns -1.

InLinuxStandard Library of functions called"AdvancedI/o "The functions that we know are knownprintf (),fopen (),fread (),fwrite()are listed here, they are also called"BufferI/O(buffered I/O)",Its characteristics are corresponding to each open file, there is a buffer in memory, each time you read a file, you will read more than a few records, so that the next time you read a file can be read directly from the memory buffer, each time the file is written, it is only written in memory buffer, etc. to meet a certain number of conditions (reached a certain amount, or encounter specific characters, such as line breaks and file terminatorsEOF), and then write the contents of the buffer once to the file, which greatly increases the speed of file read and write, but also for our programming a little bit of trouble. If there is some data that we think has been written to the file, actually because it does not meet certain conditions, they are only in the buffer, then we use_exit ()The function closes the process directly, and the data in the buffer is lost, whereas if you want to guaranteeData integrity, you must use theexit ()function.

The function of exit is declared in the stdlib.h header file.

The _exit function is declared in the unistd.h header file.

The following example compares the differences between the two functions. The printf function is how buffered I/O is used, which automatically reads the record from the buffer when it encounters a "\n" line break. Examples are compared by using this property.

exit.c Source

#include <stdlib.h> #include <stdio.h> int main (void) {printf ("Using exit...\n"); printf ("This is the content In buffer "); Exit (0); }

Output information:

Using exit ...

The content in buffer

#include <unistd.h> #include <stdio.h> int main (void) {printf ("Using exit...\n");//If "\ n" is not added here , this message may not be displayed on the terminal. printf ("The content in buffer"); _exit (0); }

Then output only:

Using exit ...

Description: After a process has called exit , the process does not immediately disappear completely, leaving behind a data structure called the zombie process (Zombie). Zombie process is a very special process, it has almost given up all the memory space, no executable code, and can not be scheduled, just keep a position in the process list, record the process's exit status and other information for other processes to collect, in addition, the zombie process no longer occupy any memory space.

#include <stdio.h>;

int main () {printf ("%c", ' C '); _exit (0);}

The difference between exit and _exit in Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.