一句话总结:exit()函数在调用exit系统之前把文件缓冲区的内容写回文件;用_exit()函数直接将进程关闭,缓冲区的数据将会丢失;atexit则是main结束后调用处理函数。
exit - cause normal process termination. void exit(int status);
_exit, _Exit - terminate the calling process "immediately". void _exit(int status); void _Exit(int status);
atexit - register a function to be called at normal process termination. int atexit(void (*function)(void));
1、看下exit()
zjy@ubuntu:~$ cat exit.cpp
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("hello boy\n");
printf("hello girl\n");
exit(0);
return 0;
}
zjy@ubuntu:~$ g++ -o exit exit.cpp
zjy@ubuntu:~$ ./exit
hello boy
hello girl
zjy@ubuntu:~$
2、看下_exit
zjy@ubuntu:~$ cat exit.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("hello boy\n");
printf("hello girl\n");
_exit(0);
return 0;
}
zjy@ubuntu:~$ g++ -o exit exit.cpp
zjy@ubuntu:~$ ./exit
hello boy
hello girl
zjy@ubuntu:~$ vim exit.cpp
zjy@ubuntu:~$ cat exit.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("hello boy\n");
printf("hello girl");
_exit(0);
return 0;
}
zjy@ubuntu:~$
zjy@ubuntu:~$ g++ -o exit exit.cpp
zjy@ubuntu:~$ ./exit
hello boy
zjy@ubuntu:~$
printf函数就是使用缓冲I/O的方式,该函数在遇到“\n”换行符时自动的从缓冲区中将记录读出,所以exit()将缓冲区的数据写完后退出,而_exit()函数直接退出。
3、看下atexit()
zjy@ubuntu:~$ cat exit.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void fun(void)
{
printf("this is fun\n");
}
int main()
{
printf("hello boy\n");
printf("hello girl\n");
atexit(fun);
printf("hello world\n");
return 0;
}
zjy@ubuntu:~$ g++ -o exit exit.cpp
zjy@ubuntu:~$ ./exit
hello boy
hello girl
hello world
this is fun