我正在尝试使用posix_spawn()来创建一个新的子进程。子进程启动后,调用者进程应该继续运行。
为什么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,那该怎么办呢?我如何发现是否有一些错误?
发布于 2020-07-08 13:25:30
从手册页(特别是第二段):
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*函数来检查子进程的结果。这将是一个好主意,因为否则你会有一个僵尸。
发布于 2020-07-08 13:25:36
posix_spawn在子进程开始之前返回,其中将检测到错误的路径。因此,子进程启动过程中的任何错误都只能通过它的退出值来检查。
如documentation中所述
返回值
成功完成后,posix_spawn()和posix_spawnp()将子进程的PID放入pid,并返回0。此外,exec(3)可能会失败。在所有这些情况下,子进程将退出,退出值为127。
错误
posix_spawn()和posix_spawnp()函数只有在底层的fork(2)、vfork(2)或clone(2)调用失败的情况下才会失败;在这些情况下,这些函数会返回一个错误号,这将是fork(2)、vfork(2)或clone(2)所描述的错误之一。此外,如果在此系统上不支持: ENOSYS函数,则这些函数将失败。
https://stackoverflow.com/questions/62787927
复制相似问题