生成“father-son-grandson”关系 的三个进程。 要求:每个进程打印自己的PID号(循环打印 10次)用c语言
时间: 2024-03-26 20:38:52 浏览: 37
好的,以下是符合您要求的代码:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
int i;
// 创建进程1
pid1 = fork();
if (pid1 < 0) {
printf("进程1创建失败\n");
return 1;
} else if (pid1 == 0) {
// 子进程1
for (i = 0; i < 10; i++) {
printf("子进程1 PID:%d\n", getpid());
sleep(1);
}
} else {
// 父进程
// 创建进程2
pid2 = fork();
if (pid2 < 0) {
printf("进程2创建失败\n");
return 1;
} else if (pid2 == 0) {
// 子进程2
// 等待子进程1结束
waitpid(pid1, NULL, 0);
for (i = 0; i < 10; i++) {
printf("子进程2 PID:%d\n", getpid());
sleep(1);
}
} else {
// 父进程
// 创建进程3
pid3 = fork();
if (pid3 < 0) {
printf("进程3创建失败\n");
return 1;
} else if (pid3 == 0) {
// 子进程3
// 等待子进程2结束
waitpid(pid2, NULL, 0);
for (i = 0; i < 10; i++) {
printf("子进程3 PID:%d\n", getpid());
sleep(1);
}
}
}
}
return 0;
}
```
这个程序创建了三个进程,分别为进程1、进程2和进程3。进程1是第一代,进程2是第二代,进程3是第三代。程序中使用了fork函数来创建进程,使用waitpid函数来等待子进程的结束。每个进程都会循环打印自己的PID号10次,并且每次打印之间会sleep一秒钟,以便我们观察。