目录
- 等待一个进程(父进程等待子进程终止)
- 僵尸进程(defunct / zombie)
- 父子进程共享同一个文件资源时,‘读写指针’ 设置
1. 等待一个进程
- 当用 fork 函数调用启动一个子进程时,子进程就有了它自己的生命周期并将独立运行。可以通过在父进程中调用 wait 函数让父进程等待子进程结束。
- wait 函数
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *stat_loc);
头文件 ‘sys/wait.h’ 中定义了用来解释状态信息的宏(每两行为一组,共 3 组):
宏 | 说明 |
---|---|
WIFEXITED(stat_val) | 如果子进程正常结束,它就取一个非零值 |
WEXITSTATUS(stat_val) | 如果 WIFEXITED 非零,它返回子进程的退出码 |
- | - |
WIFSIGNALED(stat_val) | 如果子进程因为一个未捕获的信号而终止,它就取一个非零值 |
WTERNSIG(stat_val) | 如果 WIFSIGNALED 非零,它返回一个信号代码 |
- | - |
WIFSTOPPED(stat_val) | 如果子进程意外终止,它就取一个非零值 |
WSTOPSIG(stat_val) | 如果 WIFSTOPPED 非零,它返回一个信号代码 |
- 父进程等待子进程终止,并获取/打印子进程的退出状态码,代码如下:
/* test3.c */
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void main(){
printf("main running.\n");
int res;
pid_t pid_res;
pid_t pid = fork();
switch(pid){
case 0:
// 子进程
printf("child process running.\n");
// 模拟耗时操作
sleep(5);
printf("child process done.\n");
// 指定退出码为 69(父进程将获取该退出码)
exit(69);
case -1:
// error
exit(EXIT_FAILURE);
default:
// 父进程
printf("parent process wait for child process.\n");
// 父进程执行挂起(阻塞),等待子进程终止
pid_res = wait(&res);
if(pid_res == pid){
if(WIFEXITED(res)){
printf("cp exit code(WIFEXITED): %d\n", WEXITSTATUS(res));
}else if(WIFSIGNALED(res)){