父进程中创建两个子进程
时间: 2024-05-03 14:17:30 浏览: 11
好的,可以使用fork()函数在父进程中创建两个子进程。示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
// 创建第一个子进程
pid1 = fork();
if (pid1 < 0) {
printf("Error: Failed to create first child process.\n");
exit(1);
} else if (pid1 == 0) {
printf("This is the first child process (PID = %d).\n", getpid());
exit(0);
}
// 创建第二个子进程
pid2 = fork();
if (pid2 < 0) {
printf("Error: Failed to create second child process.\n");
exit(1);
} else if (pid2 == 0) {
printf("This is the second child process (PID = %d).\n", getpid());
exit(0);
}
// 父进程等待两个子进程结束
wait(NULL);
wait(NULL);
printf("Both child processes have terminated.\n");
return 0;
}
```
这个程序会创建两个子进程,并且每个子进程都会输出它的PID。最后,父进程会等待两个子进程结束后输出一条信息。