這是我寫的使父進程等待其子進程的正確方法是什麼?
#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是的,我做 –