1.用fork函数由一个父进程生成两个子进程,并屏显三个进程的进程ID。
时间: 2023-06-11 13:10:05 浏览: 93
可以通过以下代码实现:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// 子进程1
printf("Child process 1: PID=%d\n", getpid());
return 0;
} else if (pid1 > 0) {
// 父进程
printf("Parent process: PID=%d\n", getpid());
pid2 = fork();
if (pid2 == 0) {
// 子进程2
printf("Child process 2: PID=%d\n", getpid());
return 0;
} else if (pid2 > 0) {
// 父进程
printf("Parent process: PID=%d\n", getpid());
} else {
// fork失败
printf("Fork child process 2 failed.\n");
return -1;
}
} else {
// fork失败
printf("Fork child process 1 failed.\n");
return -1;
}
return 0;
}
```
输出结果类似于:
```
Parent process: PID=1234
Child process 1: PID=1235
Parent process: PID=1234
Child process 2: PID=1236
```
其中,父进程会先执行,然后分别创建两个子进程,三个进程的进程ID分别为父进程的PID、子进程1的PID、子进程2的PID。