4)请查阅man手册,实现以下场景:父进程创建多个子进程,阻塞自身至指定子进程结束?
时间: 2024-03-07 14:47:19 浏览: 29
可以使用waitpid函数来实现父进程等待指定子进程结束的场景。waitpid函数的原型为:
```c
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
```
其中,pid参数指定要等待的子进程ID,如果pid为-1,则等待任意子进程结束;status参数用于接收子进程的退出状态;options参数指定等待选项,一般可以设置为0。
下面是一个简单的示例,父进程创建两个子进程,并等待子进程1结束后再继续执行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid1, pid2, wpid;
int status;
pid1 = fork(); // 创建子进程1
if (pid1 < 0) {
perror("fork error");
exit(-1);
} else if (pid1 == 0) {
// 子进程1的代码
printf("I'm child process 1, my pid is %d\n", getpid());
sleep(5);
printf("Child process 1 exit.\n");
exit(0);
}
pid2 = fork(); // 创建子进程2
if (pid2 < 0) {
perror("fork error");
exit(-1);
} else if (pid2 == 0) {
// 子进程2的代码
printf("I'm child process 2, my pid is %d\n", getpid());
sleep(10);
printf("Child process 2 exit.\n");
exit(0);
}
// 等待子进程1结束
wpid = waitpid(pid1, &status, 0);
if (wpid == -1) {
perror("waitpid error");
exit(-1);
} else if (wpid == pid1) {
printf("Parent process wait for child process 1 exit.\n");
}
// 继续执行父进程的代码
printf("Parent process continue to execute.\n");
return 0;
}
```
在上面的示例中,父进程创建了两个子进程,然后使用waitpid函数等待子进程1结束。当子进程1结束时,父进程才会继续执行。输出结果如下:
```
I'm child process 1, my pid is 10423
I'm child process 2, my pid is 10424
Child process 1 exit.
Parent process wait for child process 1 exit.
Parent process continue to execute.
Child process 2 exit.
```
从输出结果可以看出,父进程等待子进程1结束后,才会继续执行。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)