exit()和_exit()使用詳解

1.exit函數 html

使用exit函數,要包含頭文件」stdlib.h」,函數的使用形式爲」void exit(int status)」,參數status爲退出進程時的狀態,父進程將得到該狀態值。C語言標準指定了EXIT_SUCCESSEXIT_FAILURE做爲程序正常結束和異常終止的兩個宏。調用exit結束進程,並將結果返回給父進程。執行此函數時,會首先使用atexit函數(函數定義爲:int atexit(void (*function)(void)))註冊的函數,而後調用on_exit函數中清理動做。函數執行順序與註冊順序相反。 函數

//p1.c exit()使用實例

1 #include<stdio.h>

2 #include<stdlib.h>

3 #include<unistd.h>

4 //退出程序時的處理函數

5 void do_at_exit(void)

6 {

7 printf("You can see the output when the program terminates\n");

8 }

9 int main()

10 {

11 int flag;

12 //註冊回調函數,保存註冊結果

13 flag=atexit(do_at_exit);

14 //根據返回值判斷atexit是否成功

15 if(flag!=0)

16 {

17 printf("Cannot set exit function\n");

18 return EXIT_FAILURE;

19 }

20 //調用exit退出進程,返回Shell前調用do_at_exit函數

21 exit(EXIT_SUCCESS);

22 }



編譯及運行結果: ui

michenggang@michenggang-desktop:~/mcg$ gcc -o p1 p1.c spa

michenggang@michenggang-desktop:~/mcg$ ./p1 .net

You can see the output when the program terminates unix

michenggang@michenggang-desktop:~/mcg$ code

2._exit函數 htm

使用_exit函數,須包含「unistd.h」頭文件,函數形式爲」void _exit(int status)」,參數status爲退出時的狀態,父進程將得到該狀態值。C語言標準指定了EXIT_SUCCESSEXIT_FAILURE做爲程序正常結束和異常終止的兩個宏。_exit函數將當即結束調用它的進程,與進程相關的任何打開的文件描述符都將關閉,進程的子進程都將變爲init進程(pid=1)的子進程。使用_exit函數退出程序時,不會執行atexit中註冊的處理函數。 blog

//p2.c _exit使用實例

1 #include<stdio.h>

2 #include<stdlib.h>

3 #include<unistd.h>

4 void do_at_exit(void)

5 {

6 //進程退出時的處理函數

7 printf("You can see the output when the program terminates\n");

8 }

9 int main()

10 {

11 int flag;

12 //註冊回調函數,並保存註冊結果

13 flag=atexit(do_at_exit);

14 //根據返回結果判斷atexit執行是否成功

15 if(flag!=0)

16 {

17 printf("Cannot set exit function\n");

18 return EXIT_FAILURE;

19 }

20 //調用_exit退出進程,返回Shell前不會調用do_at_exit函數

21 _exit(EXIT_SUCCESS);

22 }



編譯及運行結果: 進程

michenggang@michenggang-desktop:~/mcg$ gcc -o p2 p2.c

michenggang@michenggang-desktop:~/mcg$ ./p2

michenggang@michenggang-desktop:~/mcg$


綜上所述,exit函數和_exit函數有以下區別:

1> exit函數在ANSIC中說明的,而_exit函數是在POSIX標準中說明

2> exit函數將終止調用進程,在退出程序以前全部文件被關閉,標準輸入輸出的緩衝區被清空,並執行在atexit註冊的回調函數;_exit函數終止調用進程,但不關閉文件,不清除標準輸入輸出的緩衝區,也不調用在atexit註冊的回調函數。

相關文章
相關標籤/搜索