posix_spawn():使用posix_spawn()时发生错误处理的问题

时间:2020-07-08 05:08:01

标签: c++ c linux multiprocessing posix

我正在尝试使用posix_spawn()创建一个新的子进程。 子进程启动后,调用者进程应继续运行。

TLDR:即使子可执行文件的路径无效(不存在),为什么posix_spawn()返回0(成功)?在这种情况下以及posix_spawn实际上已失败但返回成功的任何其他情况下,如何正确检测错误?

我尝试了以下代码。

/* The CALLER process*/
int main(int argc, char *argv) {
    int status, pid;

    printf("CALLER - Start\n");

    char *args[] = {"/home/<user>/child_exec", NULL};

    status = posix_spawn(&pid, args[0], NULL, NULL, args, environ);
    printf("Status: %d; PID: %d\n", status, pid);

    printf("CALLER - End\n");

    return 0;
}
/* The CHILD process */
int main() {
    printf("From CHILD\n");
    return 0;
}

当我运行带有正确的子可执行文件路径的调用程序时,它会按预期运行。 posix_spawn的状态为0,并打印出来自子进程的字符串。

CALLER - Start
Status: 0; PID: 5110
CALLER - End
From CHILD

现在,当我使用无效的子可执行路径运行同一程序时(例如/ home / user / child_exec123),即使子进程未执行,它仍返回状态0。

CALLER - Start
Status: 0; PID: 5251
CALLER - End

对于这种情况,子路径不存在,我可以在调用posix_spawn()之前检查文件是否存在。 但是,如果在posix_spawn()实际失败但返回0的情况下,出现类似此类的其他错误怎么办?如何查找是否有错误?

2 个答案:

答案 0 :(得分:3)

在手册页(尤其是第二段)中:

RETURN VALUE
       Upon successful completion, posix_spawn() and posix_spawnp() place  the
       PID  of  the  child process in pid, and return 0.  If there is an error
       before or during the fork(2), then no child is created, the contents of
       *pid are unspecified, and these functions return an error number as de‐
       scribed below.

       Even when these functions return a success status,  the  child  process
       may still fail for a plethora of reasons related to its pre-exec() ini‐
       tialization.  In addition, the exec(3)  may  fail.   In  all  of  these
       cases, the child process will exit with the exit value of 127.

您需要使用wait*函数之一来检查子进程的结果。无论如何,这将是一个好主意,因为否则您将有一个僵尸。

答案 1 :(得分:3)

posix_spawn在子进程开始之前返回,将检测到错误的路径。因此,子进程启动过程中的任何错误都只能通过其退出值来检查。

documentation中所述:

返回值

   Upon successful completion, posix_spawn() and posix_spawnp() place
   the PID of the child process in pid, and return 0.  If there is an
   error during the fork() step, then no child is created, the contents
   of *pid are unspecified, and these functions return an error number
   as described below.

   Even when these functions return a success status, the child process
   may still fail for a plethora of reasons related to its pre-exec()
   initialization.  In addition, the exec(3) may fail.  In all of these
   cases, the child process will exit with the exit value of 127. 

错误

   The posix_spawn() and posix_spawnp() functions fail only in the case
   where the underlying fork(2), vfork(2) or clone(2) call fails;  in
   these cases, these functions return an error number, which will be
   one of the errors described for fork(2), vfork(2) or clone(2).

   In addition, these functions fail if:

   ENOSYS Function not supported on this system.
相关问题