编写一个程序使用系统调用fork生成3个子进程
时间: 2023-04-27 21:02:07 浏览: 164
举例讲解C语言的fork()函数创建子进程的用法
可以使用以下代码来生成3个子进程:
```
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1 = fork();
if (pid1 == ) {
printf("This is child process 1, pid=%d\n", getpid());
} else {
pid2 = fork();
if (pid2 == ) {
printf("This is child process 2, pid=%d\n", getpid());
} else {
pid3 = fork();
if (pid3 == ) {
printf("This is child process 3, pid=%d\n", getpid());
} else {
printf("This is parent process, pid=%d\n", getpid());
}
}
}
return ;
}
```
运行程序后,会输出以下内容:
```
This is parent process, pid=1234
This is child process 1, pid=1235
This is child process 2, pid=1236
This is child process 3, pid=1237
```
其中,1234是父进程的进程号,1235、1236、1237分别是3个子进程的进程号。
阅读全文