Reclaim process user space resource exit () function _ exit () function atexit () function on_exit () function, _ exitatexit

Source: Internet
Author: User
Tags exit in

Reclaim process user space resource exit () function _ exit () function atexit () function on_exit () function, _ exitatexit
Abstract:This article describes how to terminate a process and how to use the exit () function to terminate the process and reclaim the user space resources of the process. It analyzes the exit () function and the _ exit () function, difference in the return keyword. it also explains in detail how to use the atexit () and on_exit () functions to register and terminate the handler.
Process Termination and Resource Recovery 1. in the kernel, the only method for executing a program is to call an exec function. the only way for a process to terminate voluntarily is to display or implicitly call _ exit () or _ Exit ().
There are five normal termination methods for processes:
(1) A common one is to execute the return statement in the main function, which is equivalent to calling exit ().
(2) Call the exit () function. Its operations include calling the end handler (registered by the atexit () or on_exit () function, which will be detailed below ), close all IO streams and so on.
(3) Call the _ exit or _ Exit function.
(4) The last thread of the process executes the return statement in its startup routine. however, the return value of this thread is not used as the return value of the process. when the last thread returns from its startup routine, the process returns in the terminated state 0.
(5) The last thread of the process calls the pthread_exit function.
There are three methods for terminating an exception: (here, I will only learn about it, but I will not discuss it in detail ).
(6) call abort. It generates the SIGABRT signal. This termination mode relies on the information transmission mechanism.
(7) When a process receives certain signals, the signals can be generated by the process itself, other processes, or the kernel.
(8) The last thread responds to the "cancel" request.
No matter how the process is terminated, the same piece of code in the kernel will be executed. disable all file descriptors and release all of their memory. for example, before a process Exits normally, you need to execute the registered exit handler (terminate the handler), refresh the stream buffer, and then release the process user space. the process control block PCB is not released at this time. only the process that calls the exit function is a zombie process.
Zombie process:In a UNIX system, a process that has been terminated but has not been processed by its parent process (obtain the information of the child process and release the occupied resources) is called a zombie process.
2. the difference between exit () and return is that exit () is used to exit a process. before the resource is officially released, the cleanup function registered by the on_exit () function and the atexit () function (terminate the handler) will be executed in reverse order, and the stream buffer will be refreshed. C language keywords return and exit () perform the same operation in the main function (Note: only in the main function, but in other places, it is different), but there are essential differences between the two:
(1) The return function exits the current function, and the exit () function exits the current process. Therefore, in the main function, return (0) and exit (0) complete the same function.
(2) return is returned only from the subfunction and does not exit the process. when you call exit (), call a termination handler and close all IO streams. the following example 1 specifically describes the difference.
3. exit () function header file: # include <stdlib>
Define the function: void exit (int status );
Function Description:
The exit () function is used to terminate the execution of the current process normally and return the parameter status (called the termination status) to the parent process. All the buffer data of the process is automatically written back and all the IO streams are closed.
Example 1: The main function uses an endless loop to call the sub-function fun (). In this example, we can see the difference between exit and return.

# Include <stdio. h> # include <unistd. h> # include <stdlib. h> int fun () {printf ("fun \ n"); sleep (1); // The Reader switches the call and returns 0; exit (0 );} int main () {int I; I ++; printf ("I = % d \ n", I); while (1) fun (); return 0 ;}


In the above example, we can see that if exit () is used in the subfunction, the loop is executed only once. If the return keyword is used in the subfunction, then the endless loop will continue to be executed.

4. _ exit () function header file: # include <unistd. h>
Define the function: void _ exit (int status );
Function Description:
_ Exit () is equivalent to _ Exit ().
The _ exit () function is used to immediately terminate the execution of the program, and return the parameter to the parent process. It exits without calling any termination handler. after this function is called, no response is returned and a SIGCHLD signal is sent to the parent process. The parent process can be ended by the wait () function. note: _ exit () does not process the standard IO buffer. If the buffer is updated, use exit ().
Example 2: Check the difference between the exit function and the _ exit function.
# Include <stdlib. h> # include <stdio. h> # include <unistd. h> int main () {printf ("output \ n"); printf ("content int buffer"); // \ n // _ exit (0) is not included ); // only output, no buffer cleared (not refreshed) exit (0); // change to this sentence to output content int buffer // return 0 ;}


As shown in example 2, when _ exit () is called to exit, the refresh buffer is not cleared. when terminating a program, _ exit () immediately enters the kernel, while exit () First executes some cleanup handler.

5. atexit () and on_exit () function header files: # include <stdlib. h>
Define functions:
Int atexit (void (* function) (void ));
Int on_exit (void (* function) (int, void *), void * arg );
Return Value: If 0 is returned successfully, a non-0 value is returned if an error occurs.
Function Description:
The atexit () and on_exit () functions are used to register the operation functions executed before the exit () function is executed. The callback function is implemented. according to iso c, a process can register up to 32 functions, which are called termination handlers. you can call the sysconf () function to view the number of termination handlers that can be registered. the order in which exit () calls these functions is the opposite of the order in which they are registered. if the same function is registered multiple times, it will also be called multiple times. the difference between the functions atexit () and on_exit () is only in the function parameters.
The parameter of the atexit () function is the address of a function and the type is void (* function) (void). When you call this function, you do not need to pass any parameters to it, it is not expected to return a value.
The parameter of the on_exit () function is a function with parameters. The type is void (* function) (int, void *). In this function void (* function) (int, in void *), the first parameter is the exit status. When you execute the exit () function, pass the parameter whose value is the exit () function. the second parameter is user input information. It is a non-type pointer. You can specify a code position or output information. (This is a bit tricky. Let's take a look at the example 3 below .)
Example 3: describes how to use the atexit () function.
# Include <stdlib. h> # include <stdio. h> # include <unistd. h> static void my_exit1 (); static void my_exit2 (); int main () {int I = 0; if (atexit (my_exit2 )! = 0) {printf ("can't register my_exit2") ;}for (I = 0; I <3; I ++) {if (atexit (my_exit1 )! = 0) {printf ("can't register my_exit1") ;}} printf ("main exiting .... \ n "); return 0; // exit (0); // same as return 0; // _ exit (0 ); // This is different} static void my_exit1 () {printf ("first exit handler... \ n ");} static void my_exit2 () {printf (" second exit handler... \ n ");}


Output:

: Main exiting ....
: First exit handler...
: First exit handler...
: First exit handler...
: Second exit handler...

Every time the processing program is registered, it will be called. in the above example, the first termination handler is registered three times, so it will also be called three times. in addition, the call sequence is the opposite of the registration sequence, which reminds us of the stack principle, First, Second, First, first, and foremost.
Note: here, the main function calls return 0 (the same as exit (), but if _ exit () is called, the output result is different. the program will only output main exiting ..... because _ exit () does not call the cleaning function.
Example 4: describes how to use the on_exit () function.
#include <stdio.h>#include <stdlib.h>static void test_exit(int status,void *arg);int main(){        char *str = "How to use on_exit function...\n";        on_exit(test_exit,(void *)str);        exit(1314);        //return 520;}static void test_exit(int status,void *arg){        printf("before exit()!\n");        printf("exit:%d\n",status);        printf("arg=%s\n",(char *)arg);}


Output:

: Before exit ()!
: Exit: 1314
: Arg = How to use on_exit function...

It can be seen that there is a relationship between on_exit () and exit () to terminate the processing program test_exit. the two parameters of the test_exit () function are obtained from "others. NOTE: If return 520 is used here, the effect will be the same. You can try it.
Example 5: Call the _ exit () function in the terminate handler. This is amazing. The reader may guess it will be the result. Example 4 is improved to get the following program:
# Include <stdlib. h> # include <stdio. h> # include <unistd. h> static void my_exit1 (); static void my_exit2 (); static void my_exit3 (); int main () {int I = 0; if (atexit (my_exit2 )! = 0) {printf ("can't register my_exit2 \ n");} // Add part if (atexit (my_exit3 )! = 0) {printf ("can't register my_exit3 \ n") ;}for (I = 0; I <3; I ++) {if (atexit (my_exit1 )! = 0) {printf ("can't register my_exit1 \ n") ;}} printf ("main exiting .... \ n "); // return 0; exit (0); // _ exit (0);} static void my_exit1 () {printf (" first exit handler... \ n ");} static void my_exit2 () {printf (" second exit handler... \ n ");} static void my_exit3 () {printf (" three exit handler... \ n "); _ exit (0); // pay attention to this. _ exit (0);} is added );}


Output:

: Main exiting ....
: First exit handler...
: First exit handler...
: First exit handler...
: Three exit handler...

No, "second exit handler..." is not output. Why? If the _ exit () function is called in one of the terminate handlers (atexit () or on_exit (), the remaining terminate handlers will not be called, other termination process steps called by the exit () function will not be executed.
6. summary exit () will process the buffer, _ exit () will not. resources cannot be wasted. Remember to recycle the allocated resources and use them for more required processes. don't stand in the trap.
Atexit () and on_exit () are registered to terminate the handler. If you want to do something else before terminating the process, you can use these two functions to register the handler.
Exit () and return are equivalent, only in the main function.

_ Exit () is equivalent to _ Exit.

Refer:

[1] exit () function instructions. http://blog.csdn.net/u010006102/article/details/39737155.

[2] _ exit () function instructions. http://blog.csdn.net/u010006102/article/details/39740101.

[3] atexit () function instructions. http://blog.csdn.net/u010006102/article/details/39740071.

[4] on_exit () function instructions. http://blog.csdn.net/u010006102/article/details/39740021.


Author: my personal abilities are limited, just for reference. If the reader finds any errors in this article, please submit them.

-- Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Do not build a high station in the sand float, calm down and slowly accumulate -----------------------------------------Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------
The exit () and abort () functions in C ++ are used to end and exit the program. What are the differences between the two functions?

The abort () function terminates the execution of the program by sending a SIGABRT signal.
The abort () function does not clear the buffer or call the cleanup function registered with the atexit () function.

The exit () function ends the program and returns a value to the operating system to inform the program of its final state. After the exit () function is called, the control is handed over to the operating system.
Before the end of the program, the exit () function will call all functions previously registered using atexit (), call them in the LIFO order, close all open files, and delete tmpfile () all temporary files created by the function
Reference: wiki.cprogram.cn/..?ba=8f

Exit function in C Language

In the main function, we usually use return (0); to return a value.

However, this is the form of void main () in non-void cases.

Exit () is usually used in subprograms to terminate the program. after use, the program automatically ends and jumps to the operating system.

However, when using exit in main, whether or not main is defined as the value returned by void is valid, and exit does not need to be considered.

# Include <iostream>
# Include <string>
Using namespace std;

Int main ()
{
Exit (1); // equivalent to return (1 );
}
Reference: www.pconline.com.cn/...7.html

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.