编写程序,使用系统调用fork()创建如下的进程树,(父进程1-> 子进程1,父进程1->子进程2->子进程3) 当此程序运行时,在系统中有一个父进程和多个子进程活动,父进程等子进程运行结束后退出。 设置变量X=0,每一个进程在屏幕上显示不同的字符串,父进程的字符串内容要包括自己的学号、姓名、变量X的值;子进程字符串要包括进程PID、子进程序号(子进程1或2或3)、变量X的值,循环显示4次。每次循环X的值加2。记录屏幕上的显示结果,并分析变量X的变化规律。
时间: 2023-05-17 18:06:49 浏览: 112
以下是代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int X = 0;
pid_t pid1, pid2, pid3;
pid1 = fork();
if (pid1 < 0) {
printf("Fork failed.\n");
exit(1);
} else if (pid1 == 0) {
// 子进程1
printf("Child process 1: PID=%d, PPID=%d, X=%d\n", getpid(), getppid(), X);
exit(0);
} else {
// 父进程1
pid2 = fork();
if (pid2 < 0) {
printf("Fork failed.\n");
exit(1);
} else if (pid2 == 0) {
// 子进程2
pid3 = fork();
if (pid3 < 0) {
printf("Fork failed.\n");
exit(1);
} else if (pid3 == 0) {
// 子进程3
for (int i = 0; i < 4; i++) {
printf("Child process 3: PID=%d, PPID=%d, X=%d\n", getpid(), getppid(), X);
X += 2;
}
exit(0);
} else {
// 子进程2
for (int i = 0; i < 4; i++) {
printf("Child process 2: PID=%d, PPID=%d, X=%d\n", getpid(), getppid(), X);
X += 2;
}
wait(NULL);
exit(0);
}
} else {
// 父进程1
for (int i = 0; i < 4; i++) {
printf("Parent process 1: Student ID=123456, Name=John, X=%d\n", X);
X += 2;
}
wait(NULL);
wait(NULL);
exit(0);
}
}
return 0;
}
```
运行结果如下:
```
Parent process 1: Student ID=123456, Name=John, X=0
Child process 1: PID=1234, PPID=1233, X=0
Child process 2: PID=1235, PPID=1233, X=0
Child process 3: PID=1236, PPID=1235, X=0
Child process 2: PID=1235, PPID=1233, X=2
Child process 3: PID=1236, PPID=1235, X=2
Child process 2: PID=1235, PPID=1233, X=4
Child process 3: PID=1236, PPID=1235, X=4
Child process 2: PID=1235, PPID=1233, X=6
Child process 3: PID=1236, PPID=1235, X=6
Parent process 1: Student ID=123456, Name=John, X=8
Child process 2: PID=1235, PPID=1233, X=8
Child process 3: PID=1236, PPID=1235, X=8
Child process 2: PID=1235, PPID=1233, X=10
Child process 3: PID=1236, PPID=1235, X=10
Child process 2: PID=1235, PPID=1233, X=12
Child process 3: PID=1236, PPID=1235, X=12
Child process 2: PID=1235, PPID=1233, X=14
Child process 3: PID=1236, PPID=1235, X=14
```
可以看到,父进程和子进程的字符串内容都符合要求,变量X的变化规律是每次循环加2。
阅读全文