exit()函数

来源:互联网 发布:mac expect scp 编辑:程序博客网 时间:2024/06/04 01:13

进程的终止方式:
有8种方式使进程终止,其中前5种为正常终止,它们是
1:从 main 返回
2:调用 exit
3:调用 _exit 或 _Exit
4:最后一个线程从其启动例程返回
5:最后一个线程调用pthread_exit
异常终止有3种,它们是
6:调用 abort
7:接到一个信号并终止
8:最后一个线程对取消请求做出响应

exit()函数整个过程:
1、调用atexit()注册的函数(出口函数)
2、cleanup();关闭所有打开的流
3、最后调用_exit()函数终止进程。
  _exit做3件事(man):
  1,Any open file descriptors belonging to the process are closed
  2,any children of the process are inherited by process 1, init
  3,the process’s parent is sent a SIGCHLD signal
  exit执行完清理工作后就调用_exit来终止进程。
  


这就应该先说一下这个atexit()函数的功能了。
这是一个注册函数,一个进程注册至少32个的函数。
需要注意的是,调用的顺序和登记时的顺序刚好是相反的,可以看下面一段代码:

#include <stdio.h>#include <stdlib.h>void exit_f1(){printf("Exit function 1 called\n");}void exit_f2(void){printf("Exit function 2 called\n");}int main(void){/* post exit function 1 */atexit(exit_fn1);/* post exit function 2 */atexit(exit_fn2);return 0;}

这里写图片描述
从程序的运行结果我们就可以看出,调用的顺序和注册的顺序刚好是相反的


那么exit()和_exit()之间有什么关系呢。
简单来说,就是只要调用了_exit()函数,那么程序就会立刻退出,不会做任何的其他行为。
而当你调用了exit()时,程序退出之前要检查文件的打开情况,把文件缓冲区中的内容写回文件,就是”清理I/O缓冲”。

#include<stdio.h>#include<stdlib.h>#include<unistd.h>#pragma warning(disable:4996)//消除系统提示的警告int main(){    printf("Hello World!\n");//特别注意这里的\n,刷新缓冲区数据    printf("This is content buff");//这里没有\n    exit(0);//0代表正常退出,其余的都是异常退出,一般用1\-1}   

程序结果如下:
这里写图片描述
将两句话都打印出来了。

#include<stdio.h>#include<stdlib.h>#include<unistd.h>#pragma warning(disable:4996)//消除系统提示的警告int main(){    printf("Hello World!\n");    printf("This is content buff");    _exit(0);注意这里现在是_exit了}   

这里写图片描述

只打印出带有\n的一句。

这样我们就能很清楚的看出,exit在退出前会清除缓冲区的数据而_exit则是直接退出程序!


综上就是一些exit()函数相关的东西了

0 0
原创粉丝点击