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

时间:2023-12-13 21:42:20

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是我当时写的一个程序得到的, 代码如下:

 #include<stdio.h>
#include<unistd.h>
#include<sys/types.h> int main()
{
char p = 'c';
int i;
FILE *fp;
pid_t pid;
printf("%d\n", getpid()); fp = fopen("data.txt", "a+");
for(i = ; i < ; i++){
if(fork() > ){
printf("%c %d\n", p = 'p', i);
}
else
printf("%c %d\n", p, i);
wait(NULL);
}
fprintf(fp, "%d %d\n", getppid(), getpid()); fclose(fp);
return ;
}