fork/exec/waitpid问题

Jim*_*ian 5 c fork exec waitpid execvp

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

   }
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*ell 5

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! */
}
Run Code Online (Sandbox Code Playgroud)