Automatically clear resources when the program exits-atexit

Source: Internet
Author: User

There are often multiple exit procedures in the program, and some cleaning work should be performed when the program exits. If there is a method that can provide no relation to the program exit method to process the program exit, it is necessary to simplify programming. Atexit () is such a method.

The atexit () statement is as follows:

extern "C" int atexit (void (*func)(void)) noexcept;extern "C++" int atexit (void (*func)(void)) noexcept;

 

The atexit parameter is a non-parameter function pointer, which is automatically executed when the program Exits normally.

There are eight ways to terminate the process, the first five of which are normal termination, they are

1: return from main

2: Call exit

3: Call _ exit or _ exit

4: The last thread returns from its startup routine

5: The last thread calls pthread_exit.

There are three types of exceptional termination:

6: call abort

7. receive a signal and terminate

8: The last thread responds to the cancellation request.

Atexit supports registration of up to 32 functions (different platforms may be different, but at least 32 functions). These functions are called in reverse order when the program exits. The same function can be registered multiple times.

If the registered function is successfully executed, a non-zero value is returned; otherwise, 0 is returned.

Below is a small example:

#include <stdio.h>      /* puts */#include <stdlib.h>     /* atexit */void fnExit1 (void){  puts ("Exit function 1.");}void fnExit2 (void){  puts ("Exit function 2.");}int main (){  atexit (fnExit1);  atexit (fnExit1);  atexit (fnExit2);  puts ("Main function.");  return 0;}

 

The running result is as follows:

This article is also published at: Hey, stay tuned

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.