【发布时间】: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 是的