【问题标题】:C : how to handle all the exit code status for bash commandsC:如何处理 bash 命令的所有退出代码状态
【发布时间】:2021-05-06 16:57:48
【问题描述】:

我正在用 C 模拟 bash。

我在尝试处理某些命令的退出状态代码时遇到了这个问题。

例如:

bash-3.2$ ./asid
bash: ./asid: No such file or directory
bash-3.2$ echo $?
127
bash-3.2$ .
bash: .: filename argument required
.: usage: . filename [arguments]
bash-3.2$ echo $?
2
bash-3.2$ 

在上面的示例中,当命令执行 bash 在 $? 中设置退出状态时,我试图在我的代码中模拟相同的行为。

到目前为止我的代码:

int     ft_exec(t_simple_cmd *cmd, t_env **head)
{
    int     pid;
    int     status;
    int     f_status;


    if (!(pid = fork()))
    {
        //child_process;
        if (execve(cmd->command, ft_args_to_arr(cmd), ft_list_to_arr(head)) == -1)
            ft_put_err(cmd->command, ft_strjoin(": ", strerror(errno)), 2);
        exit(errno);
    }
    else if (pid == -1)
    {
        //error;
        ft_putstr_fd("Fork failed.\n", 2);
    }
    else
    {
        //parent process;
        waitpid(pid, &status, 0);
        f_status = WEXITSTATUS(status);
        return (f_status);
    }
    return (1);
}

当我在 bash 中尝试相同的命令时,我会得到不同的结果。

【问题讨论】:

  • 请发布minimal reproducible example,这将包括完整可运行代码、输入、所需输出和实际输出。
  • 要明确的是,您的 ft_exec 调用是否应该返回放入您的 shell 中的值,相当于 $? ?
  • @pilcrow 是的

标签: c bash


【解决方案1】:

如果我理解正确,您最终会将ft_exec(_cmd_, _env_) 的int 返回值放入您的shell 中,相当于sh 中的$? 变量。

$? 的 POSIX specification 施加了许多限制:8 位信息,正常进程终止表示为数字 0-125,shell 扩展或重定向错误在 1-125 之间,非可执行文件调用失败为 126,缺少命令为 127,信号死亡为大于 128。

考虑到这一点,这个逻辑:

if (execve(...) == -1) {
  exit(errno);  // This is incorrect!
}

不可能是正确的。您需要自己将execve's errors 翻译成126 或127 的$?。

【讨论】:

  • 感谢您的帮助。但我有问题:例如在sh 中,当错误bash: ./sopajpd: No such file or directory 退出状态为127 但当我尝试您的回答时,退出代码为2。
  • 不,我的回答是自己返回 127。不要不要传递errno。
猜你喜欢
  • 1970-01-01
  • 2010-10-20
  • 2013-02-10
  • 2018-09-18
  • 2011-07-08
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多