* 进程等待就是等待子进程的状态改变,获取子进程的退出状态码, 允许系统释放子进程的所有资源,这时候子进程在所有资源才会被释放掉。
* 进程等待是避免产生僵尸进程的主要方式
进程等待的方式:
1. pid_t wait(int *status)
status 用于获取子进程 退出状态码
返回值是返回退出的子进程pid
wait 函数目的就是为了等待任意一个子进程的退出
因为wait是一个阻塞型的函数,因此如果没有子进程退出
那么他就一直等待,直到有子进程退出
2. pid_t waitpid(pid_t pid, int *status, int options);
pid: -1:等待任意子进程 >0 等待指定的子进程
status: 获取退出状态码
options:0:阻塞 WNOHANG:非阻塞
返回值:-1:出错 ==0:没有子进程退出 >0:退出的子进程pid
waitpid是一个阻塞/非阻塞可选的函数
具体代码实现:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
pid_t pid = fork();
if (pid < 0) {
exit(-1);
}else if (pid == 0) {
sleep(3);
exit(99);
}
pid_t id = -1;
if ((id = wait(NULL)) < 0) {
perror("wait error");
}
int status = -1;
while((id = waitpid(pid, &status, WNOHANG)) == 0) {
//可以看一看c与指针
//回过头再判断一下有没有子进程退出
}
if ((status & 0x7f) == 0) {
printf("child exit status:[%d]\n", (status >> 8)&0xff);
}
if (WIFEXITED(status)) {
printf("child exit status:[%d]\n", WEXITSTATUS(status));
}
while(1) {
sleep(1);
}
printf("child :%d eixt %d\n", id, pid);
return 0;
}
进程退出:
其中主要退出形式有:1.代码运行完毕退出 A 结果正确 B结果不正确
2.代码异常退出
正常中止:1. main函数中return
2. exit(int status)库函数调用在程序任意位置调用都会使进程退出
status是进程的退出状态
3. _exit(int status)系统调用接口在程序任意位置调用都会使进程退出
exit最终调用的就是这个接口退出的
exit与_exit的区别
* exit是温和性的退出,在退出前会温和的释放资源,刷新缓冲区
* _exit是暴力退出,直接释放资源退出,不会刷新缓冲区
具体demo如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int errno;
int main()
{
int i;
for (i = 0; i < 255; i++) {
printf("%s\n", strerror(i));
}
printf("%s\n", strerror(errno));
perror("fdgfhgj");
printf("hello world");
//exit(0);
_exit(0);
sleep(3);
return 0;
}