预备知识:缓冲区的刷新方式
- fflush(stdout)
- \n能启动刷新缓冲区的作用
1.进程终止的5种方式
- 正常退出
从main函数返回–语言级别的返回操作
调用exit–C库函数
调用_exit–系统调用 - 异常退出
调用abort 产生SIGAORT信号
由信号终止 ctrl+c /SIGINT
2.exit和_exit的区别
- 退出时,缓冲区是否会刷新
exit在退出进程之前会先刷新缓冲区
_exit不会自动清空缓冲区,必须[手动调用fflush , 加上\n]才能刷新
int main(void){
printf("hello itcast");
//exit(0);//不需要程序员手工刷新缓冲区
fflush(stdout);//不加这句话--不会刷新缓冲区--不会打印
_exit(0);
}
- exit会调用注册的终止处理程序
[1]atexit可以注册终止处理程序,ANSI C规定最多可以注册32个终止处理程序。
[2]终止处理程序的调用与注册次序相反
int atexit(void (*function)(void)); //man 2 atexit
示例代码:
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <signal.h>
void bye1(void){
printf("bye1...do\n");
}
void bye2(void){
printf("bye2...do\n");
}
int main(){
atexit(bye1);
atexit(bye2);
printf("hello.... fddddddddd1111");
fflush(stdout);
//exit(0)是c库函数 =======其他操作。。。。在调用_exit
_exit(0); //系统调用--不会调用终止处理程序
}
int main02(){
atexit(bye1);
atexit(bye2);
printf("hello.... fddddddddd1111\n");
//abort();
//exit(0); //是c库函数 =======调用终止处理程序。在调用_exit
return 0;//main函数结束时也会隐式地调用exit函数
}