| 关键词: nbsp exit exitHandler void function cout atexit main endl called |
概述 正常退出 从main函数返回[return] 调用exit 调用_exit 异常退出 调用abort 产生SIGABOUT信号 由信号终止 Ctrl+c [SIGINT]测试[exit/_exit][cpp] view plaincopy//尝试查看该程序的打印输出 #include <unistd.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { cout << "In main, pid = " << getpid(); //去掉了endl; //原理:与终端关联,stdout为行缓冲,在文件中,为全缓冲; //详细信息请参考《UNIX环境高级编程》相关章节 //exit(0);为C库函数,详细解释如下 _exit(0); } 由图可知,系统调用_exit直接陷入内核,而C语言库函数是经过一系列的系统清理工作,再调用Linux内核的[cpp] view plaincopyint main() { cout << "In main, pid = " << getpid(); fflush(stdout); //增加了刷新缓冲区工作 _exit(0); } 总结exit与_exit区别 1)_exit是一个系统调用,exit是一个c库函数 2)exit会执行清除I/O缓存 3)exit会执行调用终止处理程序 //终止处理程序如下 终止处理程序:atexit[cpp] view plaincopy#include <stdlib.h> int atexit(void (*function)(void)); 测试程序:[cpp] view plaincopyvoid exitHandler1(void) { cout << "If exit with exit, the function exitHandler will be called1" << endl; } void exitHandler2(void) { cout << "If exit with exit, the function exitHandler will be called2" << endl; } int main() { cout << "In main, pid = " << getpid() << endl; atexit(exitHandler1); //注意,先注册的后执行 atexit(exitHandler2); exit(0); } 异常终止[cpp] view plaincopyvoid exitHandler1(void) { cout << "If exit with exit, the function exitHandler will be called1" << endl; } void exitHandler2(void) { cout << "If exit with exit, the function exitHandler will be called2" << endl; } int main() { cout << "In main, pid = " << getpid() << endl; atexit(exitHandler1); atexit(exitHandler2); abort(); //exit(0); } |
|
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除
|