这是我写的使父进程等待其子进程的正确方法是什么?
#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++'无关 – alexeykuzmin0
@OliverCharlesworth是的,我做 –