wait,exit,fork
wait,用来收尸。
/*一下代码 两个进程在执行*/
if(subpid >0){
/* main process code */
/**
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);,注意里面是地址
阻塞的等待任一子进程退出,一旦发现子进程退出该函数返回
返回值 就是 那个退出的子进程的pid 同时给子进程收尸,彻底释放子进程所有资源,因为exit了之后会保存原因号码,但其他的都没有了
1.如果子进程先退出,立马获取并返回(若子进程先退出,父进程之后再wait,父进程依旧可以收尸)
2.如果父进程先死,子进程就托付给爷爷
status保存了子进程的退出码,保存在了 8-15位,注意计算机时从右往左排的
注意,因为计算机父进程往往不知道另一个子进程的退出原因号码,所以退出码再父进程当中被定义并不赋值。
eg:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
int subpid = fork();
//int status = 8;
if(subpid < 0){
printf("error");
exit(0);
}
if(subpid == 0){
printf("child.pid is %d,ppid is %d\n",getpid(),getppid());
exit(0);
}else if(subpid > 0){
sleep(3);
int status;
printf("this is father");
int recycle = wait(&status);
printf("father, recycled pid is %d, the result is %d",recycle,(status>>8)&0xFF);
//printf("father, recycled pid is %d, the result is %d",recycle,status);
exit(0);
}
}
*/
fork,完全复制当前的进程到一个新的进程
/*
int fork(void);
返回值: -1 表示失败, 克隆失败 ,当前只有一个进程
0,表示 当前进程是一个 子进程
>0: 表示 父进程, 返回值是 孩子的 pid号
*/
exit
### 进程的终结
1.退出main,(return) 本质上其实调用exit( )
2.进程调用exit主动结束自己
#include <stdlib.h>
void exit(int status);
exit会释放掉 进程绝大部分资源,但是留有#尸体#在系统中,尸体中保存了退出码status
等待父亲的收尸. 父亲收尸彻底清理掉所有资源,获取退出码 ....
一般 status : 0-正常退出
其他的码,表示不同的原因
3. _exit(int status)
和exit区别: eixt函数其实内部调用_exit实现进程推出的
但是exit在调用_exit结束进程之前,会做一些清理工作
主要是清理文件缓存,到硬盘. 比_exit安全.
总结:
其实上面三种在方法,最终都是调用_exit函数,保留尸体在系统中.
exit函数 他是安全版本.建议使用
#### 父进程 收尸
父进程调用 wait函数,来收尸.
如果父进程先死,子进程会托付给 爷爷进程.....,最终可以托付给init进程.
浙公网安备 33010602011771号