使用系统调用fork()创建test.c的两个子进程
时间: 2024-03-03 10:53:28 浏览: 19
可以使用以下代码来创建两个子进程:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
int pid1, pid2;
pid1 = fork(); // 创建第一个子进程
if (pid1 == 0) { // 子进程代码
printf("I am the first child process, my pid is %d\n", getpid());
} else if (pid1 > 0) { // 父进程代码
pid2 = fork(); // 创建第二个子进程
if (pid2 == 0) { // 第二个子进程代码
printf("I am the second child process, my pid is %d\n", getpid());
} else if (pid2 > 0) { // 父进程代码
printf("I am the parent process, my pid is %d\n");
} else { // 创建第二个子进程失败
printf("Failed to create second child process\n");
}
} else { // 创建第一个子进程失败
printf("Failed to create first child process\n");
}
return 0;
}
```
在上面的代码中,我们首先调用 `fork()` 函数创建第一个子进程,然后判断当前进程是否为子进程。如果是子进程,则输出一条消息;如果不是,则再次调用 `fork()` 函数创建第二个子进程,并分别判断当前进程是父进程、第一个子进程还是第二个子进程,并输出相应的消息。
需要注意的是,`fork()` 函数会返回两次,一次在父进程中返回子进程的进程ID,另一次在子进程中返回0。因此,我们需要在代码中根据返回值来判断当前进程是父进程还是子进程。