exit()和_exit()使用详解

1.exit函数

使用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 }



编译及运行结果:

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

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

You can see the output when the program terminates

michenggang@michenggang-desktop:~/mcg$

2._exit函数

使用_exit函数,须包含“unistd.h”头文件,函数形式为”void _exit(int status)”,参数status为退出时的状态,父进程将获得该状态值。C语言标准指定了EXIT_SUCCESSEXIT_FAILURE作为程序正常结束和异常终止的两个宏。_exit函数将立即结束调用它的进程,与进程相关的任何打开的文件描述符都将关闭,进程的子进程都将变为init进程(pid=1)的子进程。使用_exit函数退出程序时,不会执行atexit中注册的处理函数。

//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注册的回调函数。

你可能感兴趣的:(c,linux,进程通信,exit())