【问题标题】:fork/exec/waitpid issuefork/exec/waitpid 问题
【发布时间】:2012-11-24 00:04:23
【问题描述】:

我试图通过检查 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.
   {

   }
}

【问题讨论】:

  • WIFEXITED用于区分WIFSIGNALED和WIFSTOPPED。在正常情况下,当孩子失败(以非零状态退出)时,WIFEXITED 为真。您需要同时检查WIFEXITED 和WEXITSTATUS。

标签: c exec fork execvp waitpid


【解决方案1】:

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! */
}

【讨论】:

  • 感谢您的回复。它第一次实际选择了一个不成功的执行——然而,它现在似乎认为所有的执行都是不成功的......如果我不关心子进程失败的确切原因是什么,不应该添加我第一次更新的第一篇文章中的代码就足够了吗?
猜你喜欢
  • 2012-08-29
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 2015-12-01
  • 2016-03-19
相关资源
最近更新 更多