我正在尝试使用posix_spawn((创建一个新的子进程。子进程启动后,调用方进程应继续运行。
TLDR:为什么即使子可执行文件的路径无效(不存在(,posix_spawn((也会返回0(成功(?如何正确检测这种情况下的错误,以及posix_spown实际失败但返回成功的任何其他情况?
我尝试了以下代码。
/* The CALLER process*/
int main(int argc, char *argv) {
int status, pid;
printf("CALLER - Startn");
char *args[] = {"/home/<user>/child_exec", NULL};
status = posix_spawn(&pid, args[0], NULL, NULL, args, environ);
printf("Status: %d; PID: %dn", status, pid);
printf("CALLER - Endn");
return 0;
}
/* The CHILD process */
int main() {
printf("From CHILDn");
return 0;
}
当我运行带有正确子可执行文件路径的调用程序时,它会按预期运行。posix_spown的状态为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,该怎么办?如何查找是否存在错误?
来自手册页(特别是第二段(:
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*
函数来检查子进程的结果。无论如何,这都是个好主意,否则你会有一个僵尸。
posix_spawn
在子进程启动之前返回,在该进程中将检测到不正确的路径。所以,在启动子进程的过程中,您只能通过它的退出值来检查任何错误。
如文件所述:
返回值
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.