eg:exit() _exit()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
printf("this is exit\n");
#if 0
//_exit 进程终止函数,不清理缓冲区的内容,进程直接结束
printf("_exit test");
_exit(0);
#else
//exit 进程终止函数,清理缓冲区的内容,然后进程结束
printf("exit test");
exit(0);
#endif
}
eg:wait()
//阻塞函数,在父进程不运行的情况下用于回收子进程(父进程不运行,子进程运行就是孤儿进程,必须有一父一子。)
//wait()返回值是子进程的进程id
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int pid=fork();
if(pid>0){
printf("this is main process start\n");
wait(NULL);
printf("this is main process over\n");
}
else if(pid==0){
for(int i=0;i<5;i++){
printf("this is child\n");
sleep(1);
}
}
}
eg: WEXITSTATUS宏
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int pid=fork();
if(pid>0){
int ret;
printf("this is main process start\n");
int pid_p=wait(&ret);//等待子进程结束 返回值:子进程退出的进程号,&ret 获取子进程退出的进程id
printf("ret:%d\n",ret);
if(WIFEXITED(ret)) //判断子进程是否调用exit _exit函数 正常退出
printf("wait status ret:%d\n",WEXITSTATUS(ret));//获取exit里的值
printf("this is main process over,pid_p:\n",pid_p);
}
else if(pid==0){
for(int i=0;i<5;i++){
printf("this is child\n");
sleep(1);
}
//abort();//程序异常退出
exit(10);
}
}
eg:waitpid()
1.png