我已經看過關於這個的一些主題後的等待(),但未能解決這個問題 -憋屈fork()的
我分叉兩次,但等待最後PROC當它卡住上等待() ,如果我刪除的wait(),它移動,但顯然它不會等待:
這裏是有關的代碼:
/*Fork #1*/
if((pid=fork())==0)
{
if(command -> inputRedirect != NULL)
{
fclose(stdin);
fopen(command -> inputRedirect,"r");
}
fclose(stdout);
dup(pipefd[1]);
close(pipefd[1]);
i=execvp(command->arguments[0],command->arguments);
}
if(i == -1)
{
perror("Error");
return 1;
}
printf("\nParent: %d , Child: %d\n",getpid(),pid);
command = command->next;
/*Fork #2*/
if((pid=fork())==0)
{
fclose(stdin);
dup(pipefd[0]);
close(pipefd[0]);
if(command -> outputRedirect != NULL)
{
fclose(stdout);
fopen(command ->outputRedirect,"w");
}
i=execvp(command->arguments[0],command->arguments);
_exit(0);
}
if(i == -1)
{
perror("Error");
return 1;
}
if(command->blocking == 1)
{
int test=0;
printf("\nParent: %d , Child: %d\n",getpid(),pid);
printf("\ntest1\n");
while((test=wait(NULL)) != pid)
{
printf("\n %d \n ", test);
}
printf("\ntest2\n");
}
return 0;
}
我加了一些測試,看看一些PID輸出和最新內部運行,它等待第一個chil進程完成,並打印正確的ID,但第二個只是阻止。
但是我在屏幕上看到第二個過程完成(從過程輸出)。
任何有關該主題的幫助將是最受歡迎的。
謝謝。
聽起來像第二個孩子不會退出。 –
流程輸出不一定是它是否退出的可靠指標。改爲通過'ps'命令檢查過程列表。 –
不過,我不認爲是這樣,有兩個原因 - 如果一個孩子退出,它仍然是一個「殭屍」,直到等待被調用,其次,如果沒有孩子procsess調用wait()什麼也不做,我有嘗試不同的代碼變化,不用一段時間,仍然阻止:/ –