gpt4 book ai didi

c - 我无法退出我的程序

转载 作者:行者123 更新时间:2023-11-30 19:44:25 24 4
gpt4 key购买 nike

我正在尝试做一个像 bash 这样的命令解释器,但遇到了一些问题。

当我执行像 ls/cat/grep 这样的现有命令时,它可以正常工作,但是当我尝试执行像 qsdjhkoqd 这样的命令时,它会说命令未找到,如果我尝试在它之后退出,它不会退出。

例如,如果我做了 4 条不好的评论,我将不得不退出 5 次才能退出我的程序。我知道这肯定是一个过程问题,但我不知道如何解决它,你能告诉我哪里错了吗?

谢谢!

int im_your_father(t_struct *tool, char **env, char **argv)
{
int ret;

ret = 0;
if (tool->command.pid == 0)
{
ret = execve(tool->command.command, argv, env);
}
else
wait(NULL);
return (ret);
}

int execute_path(t_struct *tool , char **env ,
char **argv, t_first_elem *list)
{
int i;
int ret;

tool->command.pid = fork();
(void)list;
i = -1;
if (my_strcmp("ls", argv[0]) == 0)
{
while (argv[++i] != NULL)
;
argv[i] = my_strdup("--color=auto");
argv[++i] = NULL;
i = -1;
}
while (tool->path[++i] != NULL)
{
tool->command.command = my_strdup_mod(tool->path[i],
my_strlen(tool->command.line));
my_strcat(tool->command.command, "/");
my_strcat(tool->command.command, argv[0]);
ret = im_your_father(tool, env, argv);
if (ret != -1)
return (0);
}
if (tool->command.pid == 0)
{
my_putstr("son alive");
}
else
{
printf("%d\n", tool->command.pid);
wait(NULL);
}
my_putstr(argv[0]);
my_putstr(": command not found\n");
return (0);
}

最佳答案

我认为问题主要在于以下几行:

if (tool->command.pid == 0)
{
ret = execve(tool->command.command, argv, env);
}

首先,不需要捕获 execve() 的返回值。如果成功,就永远不会返回;如果它真的返回,那么它就失败了。

其次,您需要考虑接下来会发生什么,简短的答案是您现在有两个进程,它们都认为它们是您的 shell。现在你有两个进程试图读取你的输入,它们争论谁获得每个字符,结果是一团糟,就像人类的 child 争论轮到谁使用最喜欢的玩具一样。

大多数时候,尤其是在 shell 中,如果 execve() 失败,您可能会想要退出,可能是在产生错误消息之后:

if (tool->command.pid == 0)
{
execve(tool->command.command, argv, env);
fprintf(stderr, "failed to execute %s (%s)\n", tool->command.command, strerror(errno));
exit(127);
}

确切的退出状态是可以协商的;我通常只使用 1,但 POSIX 标准确实规定 exit statuses当执行命令失败时:

If a command is not found, the exit status shall be 127. If the command name is found, but it is not an executable utility, the exit status shall be 126.

关于c - 我无法退出我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com