进程退出的几种方式
当程序执行出错时,如果会导致后续的程序无法再执行下去,此时应该终止程序运行,而终止程序执行通常有如下几种方式。
1.return
在main函数中执行return可以终止进程,并将控制权交给调用函数。一般原则程序执行正常退出return 0,而执行函数出错退出return -1。
2.exit
exit()是一个标准C库函数,执行exit()会进行一些清理工作,最后调用_exit()函数。
函数原型:
void exit(int status);
3._exit()和_Exit()
_Exit()和_exit()等价,都属于系统调用,使用_exit()会清除其使用的内存空间,并销毁其在内核中的数据结构,关闭进程的所有文件描述符,并结束进程、将控制权交给操作系统。
函数原型:
void _exit(int status);
调用函数需要传入status状态标志,0表示正常结束、若为其它值则表示程序执行过程中检测到有错误发生。
实例代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int fd;
/* 打开文件 */
fd = open("/tmp/test.txt", O_RDONLY);
if (-1 == fd) {
perror("open file failed");
_exit(-1);
}
close(fd);
_exit(0);
}