使用exit() 和 _exit()可以终止一个进程。
1.exit()
函数原型:
#include <stdlib.h> //exit()需要引入
#include <unistd.h> //_exit()需要引入
void exit(int status); //status表示退出状态,一般成功设置为0,失败设置为非0
void _exit(int status);
exit()和 _exit()函数功能和用法是一样的,区别就是所包含的头文件不一样(exit需要stdlib.h,而_exit需要unistd.h),另外exit()属于标准库函数,_exit()属于系统调用函数。最重要的区别就是exit() 函数,会刷新 I/O 缓冲区,而_exit()不会刷新缓冲区。

实例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
//注意:如果字符串后带\n换号符号,那么exit和_exit都会刷新缓冲区。
printf("hi, you are welcome!");
exit(0); // 结束进程,标准库函数,刷新缓冲区,printf()的内容能打印出来
//_exit(0); // 结束进程,系统调用函数,printf()的内容不会显示到屏幕
while(1); // 不让程序结束
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
hi, you are welcome![root@iz2zefozq9h39txdb8s7npz shelldemo]#
2.exit与return的区别
return 的作用是结束调用 return 的所在函数,只要这个函数不是主函数( main() ),只要主函数没有结束,return 并不能结束进程。
实例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void fun()
{
printf("this is fun() function!\n");
//return; //函数返回
exit(0); //退出进程
printf("hello,world!\n"); //不会输出...
}
int main(int argc, char *argv[])
{
printf("this is main function!\n");
fun();
printf("after fun()\n");
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
this is main function!
this is fun() function!