在系统中有大量的进程时,有可能会让系统资源消耗殆尽。因此,要在用完进程后终止进程。Linux用到的函数为exit和_exit函数。当程序执行exit和_exit时,进程会条件地停止所有操作,终止本进程的运行。这两个数的区别如图 7‑2所示:
![]()
从图中可以看出,_exit函数的作用是:直接使进程停止运行,清除其使用内存空间,并清除其在内核中的各种数据结构;exit函数则在这些基础上作了一些动作,在执行退出之前加了若干道工序。Exit函数和 _exit函数最大的区别就在于exit函数在调用exit系统调用前要检查文件的打开情况,把文件缓冲区中的内容写回文件。就是图中的“清理I/0缓冲”。
2. exit和_exit函数语法
![]()
3. exit和_exit函数实例
print函数使用的是缓冲I/0方式,该函数在遇到“\n”换行符时自动从缓冲区中将记录读出。以下实例就是利用此性质来进行比较。
/*exit.c*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t result;
result=fork();
if(result==1)
{
perror("fork fail");
exit(0);
}
else if(result==0)
{
printf("testing _exit()\n");
printf("this is the content in buffer");
_exit(0);
}
else
{
printf("testing exit()\n");
printf("this is the content in buffer");
exit(0);
}
}
运行结果为:
[root@localhost exit]#./exit
testing _exit()
testing exit()
this is the content in buffer
从实例结果来看,exit函数前的字符串输出了两句,_exit()函数前的字符串输出一句。这也说明调用exit函数时,缓冲区的记录能正常输出;而调用_exit函数时,缓冲区中的记录无法输出。
|
http://www.weicedu.com/forum.php?mod=viewthread&tid=113&fromuid=4
(出处: http://www.weicedu.com/)