自行设计一段代码,要求父进程至少创建2个子进程,每个子进程执行内容不同。父进程在所有子进程结束后才能结束。
时间: 2024-05-09 08:17:42 浏览: 10
好的,以下是您所要求的代码段,实现了父进程创建2个子进程,每个子进程都执行不同的内容,父进程在所有子进程结束后才能结束。
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0) {
perror("fork error");
exit(EXIT_FAILURE);
}
else if (pid1 == 0) {
// code for child process 1
printf("This is child process 1 with PID %d\n", getpid());
exit(EXIT_SUCCESS);
}
else {
pid2 = fork();
if (pid2 < 0) {
perror("fork error");
exit(EXIT_FAILURE);
}
else if (pid2 == 0) {
// code for child process 2
printf("This is child process 2 with PID %d\n", getpid());
exit(EXIT_SUCCESS);
}
else {
// code for parent process
int status;
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
printf("All child processes have terminated. Parent process with PID %d is now exiting.\n", getpid());
exit(EXIT_SUCCESS);
}
}
return 0;
}
```
希望这段代码能够满足您的要求。如果您有其他问题,可以继续向我提问。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)