2012-12-06 77 views
4

我試圖確定執行是否通過檢查waitpid函數的結果失敗()。但是,即使當我跑,我知道失敗並寫入這個問題到stderr命令,檢查以下從未登記。這段代碼可能有什麼錯誤?叉/ EXEC/waitpid函數問題

感謝您的任何幫助。

pid_t pid; // the child process that the execution runs inside of. 
int ret;  // exit status of child process. 

child = fork(); 

if (pid == -1) 
{ 
    // issue with forking 
} 
else if (pid == 0) 
{ 
    execvp(thingToRun, ThingToRunArray); // thingToRun is the program name, ThingToRunArray is 
             // programName + input params to it + NULL. 

    exit(-1); 
} 
else // We're in the parent process. 
{ 
    if (waitpid(pid, &ret, 0) == -1) 
    { 
     // Log an error. 
    } 

    if (!WIFEXITED(ret)) // If there was an error with the child process. 
    { 

    } 
} 
+1

'WIFEXITED'用於區分'WIFSIGNALED'和'WIFSTOPPED'。在正常情況下,當孩子失敗時,「WIFEXITED」爲真(以非零狀態退出)。你需要檢查'WIFEXITED'和'WEXITSTATUS'。 –

回答

4

waitpid只返回-1,如果與waitpid發生錯誤。也就是說,如果你給它一個不正確的PID,或者被中斷,等等。如果孩子有一個失敗的退出狀態,waitpid函數會成功(返回PID),並設置ret反映孩子的情況。

確定孩子的身份,使用WIFEXITED(ret)WEXITSTATUS(ret)。例如:

if(waitpid(pid, &ret, 0) == -1) { 
    perror("waitpid"); 
} else if(WIFEXITED(ret) && WEXITSTATUS(ret) != 0) { 
    ; /* The child failed! */ 
} 
+0

感謝您的回覆。這是第一次,它實際上拿起一個執行,這是不成功的 - 但是,現在看來要考慮所有執行不成功......如果我不在乎到底是什麼子進程失敗的原因是,不應該加入代碼在我第一次更新的第一篇文章是所需要的? –

+0

哇不知何故,我錯過了代碼片斷你貼出來,是我不好。 –

+0

您的解決方案完美無缺,謝謝您的好先生! –