进程问题:fork/exec/waitpid

5
我正在尝试通过检查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.
   {

   }
}

1
WIFEXITED 用于区分 WIFSIGNALEDWIFSTOPPED。在正常情况下,当子进程失败(以非零状态退出)时,WIFEXITED 为 true。您需要检查 WIFEXITEDWEXITSTATUS - William Pursell
1个回答

6

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

感谢您的回复。这是第一次它实际上捕获到一个不成功的执行 - 然而,现在它似乎将所有执行都视为不成功... 如果我不关心子进程失败的确切原因,那么我在第一个更新的帖子中添加的代码就足够了吗? - Jim Ruffian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接