【问题标题】:Fork and execlp, how to differentiate the status and print state accordinglyfork 和 execlp,如何区分状态和打印状态
【发布时间】: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() 的返回值(如果返回)与它(未能)执行的程序的退出状态无关。

标签: c fork exec


【解决方案1】:

子进程打印“ERROR - Cannot run command\n”后,进入return 0;语句,导致进程以状态码0退出。您可以返回一些其他小的正值来更改退出码.

在 Bash shell 中运行未知命令似乎将 Bash 的 $? 变量设置为 127,所以也许这是一个合理的返回值选择。

【讨论】:

  • 我尝试在上述行之后的exit(127) 中实现,但仍然得到相同的结果。无论我使用/bin/ls 还是/bin/lsa,它仍然会告诉我这两个命令都成功了,还有ERROR - Cannot run command
  • @dissidia 我自己试过了(在printf("ERROR - Cannot run command\n"); 之后添加exit(127);),父级按预期打印Child's exit code 127。也许你忘了重新编译它?
  • 你是对的,我的错!
猜你喜欢
  • 2011-03-01
  • 2015-01-19
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2012-08-09
  • 2016-04-03
  • 1970-01-01
相关资源
最近更新 更多