[Chapter 3 Process]Practice 3.12 Including the initial parent process, how many processes are created by the program shown in Figure 3.32?

时间:2022-07-31 20:56:28

3.12 Including the initial parent process, how many processes are created by the program shown in Figure 3.32?

[Chapter 3 Process]Practice 3.12 Including the initial parent process, how many processes are created by the program shown in Figure 3.32?

答案: 共16个进程。

解析:

  根据之前所学到的关于fork的知识去画进程图, 要注意的一点就是, fork的子进程的程序计数器里的指令和父进程的相同, 所以每次fork之后, 子进程里i的值都会继续增加。例如, 第一个进程, i=0时, fork的子进程的i会继续++, 从1开始。 下面是此题的进程图。

[Chapter 3 Process]Practice 3.12 Including the initial parent process, how many processes are created by the program shown in Figure 3.32?jk

红色的数字是进程的PID, PID是我当时写的一个程序得到的, 代码如下:

 

 1 #include<stdio.h>
 2 #include<unistd.h>
 3 #include<sys/types.h>
 4 
 5 
 6 int main()
 7 {
 8     char p = 'c';
 9     int i;
10     FILE *fp;
11     pid_t pid;
12     printf("%d\n", getpid());
13 
14 
15     fp = fopen("data.txt", "a+");
16     for(i = 0; i < 4; i++){
17         if(fork() > 0){
18             printf("%c %d\n", p = 'p', i);
19         }
20         else
21             printf("%c %d\n", p, i);
22         wait(NULL);
23     }
24     fprintf(fp, "%d %d\n", getppid(), getpid());
25 
26     fclose(fp);
27     return 0;
28 }