查阅man手册,编写代码实现以下场景:父进程创建多个子进程,阻塞自身至指定子进程结束?
时间: 2024-03-17 08:45:32 浏览: 34
下面是一个实现父进程创建多个子进程的示例代码,父进程会阻塞自身至指定子进程结束:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int i, pid, status;
int num_children = 5; // 创建的子进程数量
int target_child = 3; // 指定的目标子进程
for (i = 1; i <= num_children; i++) {
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) { // 子进程
printf("Child %d (pid=%d) is created.\n", i, getpid());
sleep(i); // 模拟子进程的任务
printf("Child %d (pid=%d) is exiting.\n", i, getpid());
exit(0);
}
}
// 父进程等待指定的子进程结束
printf("Parent (pid=%d) is waiting for child %d.\n", getpid(), target_child);
waitpid(-1, &status, 0); // 等待任意子进程结束
while (WIFEXITED(status) && WEXITSTATUS(status) != target_child) {
waitpid(-1, &status, 0);
}
// 目标子进程已结束,父进程继续执行
printf("Parent (pid=%d) resumes execution.\n", getpid());
return 0;
}
```
该程序创建了5个子进程,在每个子进程中模拟了一个简单的任务。父进程等待指定的子进程结束,然后继续执行。在上面的代码中,指定的目标子进程是第3个子进程,可以根据需要修改为其他值。
相关推荐
![](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)