【发布时间】:2021-10-12 14:10:40
【问题描述】:
我指的是这个问题 - 来自 SO 的 How to get the return value of a program ran via calling a member of the exec family of functions?,因为我正在尝试类似的操作。
我使用的是execlp 命令,而不是execl 命令。作为我的代码,应该包含一个命令行参数列表,例如。 ./myCode /bin/ls /bin/date 即使参数之一错误,例如/bin/lsa,它也会打印出错误的行 - Child Exit Code 为 0。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int number, statval;
int child_pid;
printf("%d: I'm the parent !\n", getpid());
child_pid = fork();
if(child_pid == -1)
{
printf("could not fork! \n");
exit( 1 );
}
else if(child_pid == 0)
{
execlp("/bin/lsa", "/bin/ls" ,(char *) NULL);
// error
printf("ERROR - Cannot run command\n");
}
else
{
printf("PID %d: waiting for child\n", getpid());
waitpid( child_pid, &statval, WUNTRACED);
if(WIFEXITED(statval))
printf("Child's exit code %d\n", WEXITSTATUS(statval));
else
printf("Child did not terminate with exit\n");
}
return 0;
}
这是终端输出:
119: I'm the parent !
PID 119: waiting for child
ERROR - Cannot run command
Child's exit code 0
还有哪些其他方法可以改进 if-else 代码块的最后一部分?使用示例./myCode /bin/lsa /bin/date,我试图实现以下输出:
Command /bin/lsa cannot be executed
<display output of /bin/date>
Command /bin/date is a success
【问题讨论】:
-
显然你应该从孩子那里返回一个非零代码,以防出现错误,如果你的父母期望它。
-
但是当您的孩子的
execlp()失败时,其退出状态为 0。如果您希望它在这种情况下有所不同,那么让孩子return获得想要的状态,或者在打印错误消息后将其传递给_exit()。 -
嗨@EugeneSh。你可能指的是伊恩在下面提到的那个吗?
-
@JohnBollinger,如果您能详细说明一下或给我看一个简单的代码 sn-p,有什么机会吗?对此感到抱歉,因为我对这个分叉领域仍然是全新的
-
另外,我在你的代码中使用了 cmets 来表明你已经理解了这一点,但为了以防万一,必须理解
execlp()和其他 exec-family 函数根本不会返回当他们成功时。它们不能,因为它们的作用是将调用进程中运行的代码替换为另一个程序,该程序在其正常入口点输入。没有什么可以返回。由此可见,execlp()的返回值(如果返回)与它(未能)执行的程序的退出状态无关。