atexit函數的作用

來源:互聯網
上載者:User

很多時候我們需要在程式退出的時候做一些諸如釋放資源的操作,但程式退出的方式有很多種,比如main()函數運行結束、在程式的某個地方用exit()
結束程式、使用者通過Ctrl+C或Ctrl+break操作來終止程式等等,因此需要有一種與程式退出方式無關的方法來進行程式退出時的必要處理。方法就是用atexit()函數來註冊程式正常終止時要被調用的函數。

    atexit()函數的參數是一個函數指標,函數指標指向一個沒有參數也沒有傳回值的函數。atexit()的函數原型是:int atexit
(void (*)(void));

   
在一個程式中最多可以用atexit()註冊32個處理函數,這些處理函數的調用順序與其註冊的順序相反,也即最先註冊的最後調用,最後註冊的最先調用。

#include <stdlib.h>
#include <stdio.h>

void
fun()
{
    printf("fun/n");
}

int main()
{
   
atexit(fun);
    printf("hello/n");
    return 0;
}

// int atexit(void (*func)()) // 見
<stdlib.h> 中定義
// {
//     func();
//
    return 0;
// }

上面的代碼將輸出

hello

fun

而把紅色的注釋代碼去掉之後,由於Interpositioning行為,重定義了庫函數,使atexit僅僅表現為一個普通的函數

因此輸出

fun

hello

 

附一道關於atexit函數的面試題目


  main函數執行完畢後,是否可能會執行一段代碼?給出說明。


答案:

如果需要加入一段在main退出後執行的代碼,可以使用atexit()函數註冊一個函數,代碼如下:

 

 

#include <stdlib.h><br /> #include <stdio.h> </p><p> void fn1( void ), fn2( void ), fn3( void ), fn4( void ); </p><p> int r1=atexit( fn1 );<br /> int r2=atexit( fn2 );<br /> int r3=atexit( fn3 );<br /> int r4=atexit( fn4 ); </p><p> void main( void )<br /> {<br /> printf( "This is executed first./n" );<br /> } </p><p> void fn1()<br /> {<br /> printf( "next./n" );<br /> } </p><p> void fn2()<br /> {<br /> printf( "executed " );<br /> } </p><p> void fn3()<br /> {<br /> printf( "is " );<br /> } </p><p> void fn4()<br /> {<br /> printf( "This " );<br /> } </p><p> 輸出為:<br /> This is executed first.<br /> This is executed next.<br /> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.