如果我的解釋是正確的,從下面的 C 程式中,我們希望獲得一個行程樹,其中從一個父行程生成三個子行程和兩個孫子行程:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num;
pid_t t;
for (num = 0; num < 2; num ) {
t = fork();
if (t == 0)
break;
}
t = fork();
printf("I am the process %d and my father is %d\n", getpid(), getppid());
return 0;
}
但是,編譯執行后,輸出結果如下:
I am the process 2133 and my father is 2127
I am the process 2134 and my father is 2133
I am the process 2137 and my father is 778
I am the process 2135 and my father is 778
I am the process 2138 and my father is 778
I am the process 2136 and my father is 778
正如預期的那樣,產生了六個行程,但其中四個是由行程#778 產生的。另一方面,其中一個(#2134)似乎是由初始行程(#2133)創建的。總共生成了兩個行程樹而不是一個。
為什么會有這種行為?這是否意味著上述四個流程已被#778流程采用/回收?
uj5u.com熱心網友回復:
正如評論中所指出的,您不是在等待子行程在父行程中完成,因此在父行程退出后,shell 會回收孤立行程。
正確的樹結構是:
1
|
2
/ | \
3 4 5
| |
6 7
在哪里:
- 1是外殼
- 2是你的主程式;它在回圈中生成 3 和 4,在回圈后生成 5
- 3 和 4 是由 2 在回圈中產生的孩子;每個在存在回圈后產生 1 個新的孩子(6 和 7)
break - 5 在回圈之后產生,因此是一個葉行程
- 6 和 7 是回圈后由 3 和 4 產生的葉行程
這是經過清理的代碼,可以提供可理解的輸出:
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
printf("original process is %d\n", getpid());
for (int num = 0; num < 2; num ) {
if (fork() == 0) { // 0 means child
break;
}
}
fork(); // fork after the loop
printf("I am %d and my parent is %d\n", getpid(), getppid());
while (wait(NULL) > 0) {} // wait for each child process
return 0;
}
示例輸出:
original process is 540
I am 540 and my parent is 1
I am 541 and my parent is 540
I am 543 and my parent is 541
I am 542 and my parent is 540
I am 544 and my parent is 540
I am 545 and my parent is 542
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373378.html
