簡體   English   中英

fork / exec / waitpid問題

[英]fork/exec/waitpid issue

我試圖通過檢查waitpid()的結果來確定執行是否失敗。 但是,即使我運行了一條我知道失敗的命令並將該問題寫入stderr,下面的檢查也永遠不會注冊。 此代碼可能有什么問題?

謝謝你的幫助。

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.
   {

   }
}

如果waitpid發生錯誤,則waitpid僅返回-1。 也就是說,如果您給它提供了不正確的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! */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM