【发布时间】:2016-08-29 16:19:31
【问题描述】:
这是我写的程序
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<iostream>
#include<wait.h>
int main(void){
std::cout << "My process " << getpid() << std::endl;
int i;
for(i=0;i<2;i++){
int j = fork();
wait(NULL);
std::cout << "Process id :" << getpid() <<" and parent:"<< getppid()<< " and value returned is " << j <<std::endl;
}
return 0;
}
这是我得到的输出:
My process 5501
Process id :5502 and parent:5501 and value returned is 0
Process id :5503 and parent:5502 and value returned is 0
Process id :5502 and parent:5501 and value returned is 5503
Process id :5501 and parent:2828 and value returned is 5502
Process id :5504 and parent:5501 and value returned is 0
Process id :5501 and parent:2828 and value returned is 5504
有人可以向我解释一下输出吗?该程序的目的是以 DFS 方式“访问”进程。但是,我不明白第三行中返回的值是 5503 的原因,以及为什么即使我只运行了两次循环,是否会创建 5504?提前致谢。
【问题讨论】:
-
你了解
fork的操作吗? -
问题与
c++无关 -
@OliverCharlesworth 是的,我愿意
-
那你为什么在调用
fork之后又无条件地调用wait? -
目的是让父进程等到其子进程终止。我在这里读到了 [stackoverflow.com/questions/19461744/…