gpt4 book ai didi

c - C 中的虚拟 Shell 在关闭外部进程后会出现问题

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

我正在为 C 中的作业编写 shell。现在我唯一的问题是,当我使用 execvp() 调用外部程序然后使用 CTRL + C 关闭时,我发送的任何其他命令都会在提示后打印不在它之前。我制作了一个虚拟程序,它只是一个无限循环来测试它。

因此,关闭该程序后,如果我尝试运行一个不存在的程序,它将打印出来
MINISHELL (cwd) $: 然后是一个空行
然后它会打印我的错误消息,说我输入了一个不存在的程序,然后它不会打印提示,因为它已经存在了。所以它以一个空的新行结束,看起来程序还没有结束,但实际上已经结束了。

它仅在我使用 CTRL + C 关闭非终止程序后才会执行此操作。否则它可以正常执行程序。我是否没有在某处使用 close() 来关闭文件描述符?我不知道。任何帮助表示赞赏。谢谢。

#include "minishell.h"


void intHandler(int sig)
{
my_char('\n');
}

int main(int argc, char **argv)
{
int n;
int pid = 0;
char* s = (char*)malloc(256*sizeof(char));
char cwd[1024];
char** input;

while (1)
{
signal(SIGINT, intHandler);

my_str("MINISHELL:");

if (getcwd(cwd, sizeof(cwd)) != NULL)
my_str(cwd);

else
{
my_str("Error in current directory");
return -1;
}

my_str(" $: ");
n = read(0, s, 256);
s[n] = '\0';

if (n > 1)
{
input = my_str2vect(s);
if (my_strcmp(input[0], "cd") == 0)
{
/*CHANGE DIRECTORY*/
if (input[1] != '\0')
{
if (chdir(input[1]) < 0)
my_str("MINISHELL: Error in path. Make sure the directory exists.\n");
}

else
my_str("MINISHELL: Error. No directory specified.\n");
}

else if (my_strcmp(input[0], "help") == 0)
{
/*HELP*/
my_str("\nMINISHELL COMMANDS:\n\ncd *directory\nChanges the current working directory to *directory\n\nexit\nExits the minishell\n\nhelp\nPrints a help message listing the built in commands\n\n");
}

else if (my_strcmp(input[0], "exit") == 0)
{
/*EXIT*/
my_str("Thank you for using MINISHELL\n");
exit(0);
}

else if (input[0] != NULL)
{
/*EXECUTE AN EXTERNAL PROGRAM*/
if ((pid = fork()) < 0)
my_str("MINISHELL: Error forking\n");

else if (pid > 0)
{
wait(NULL);
}

else
{
if (execvp(input[0], input) < 0)
{
my_str("MINISHELL: Error. Program does not exist in current directory.\n");
}

else
{
exit(0);
close(0);
}
}
}

else
{
my_str("MINISHELL: Error reading command. Type help to see available commands.");
}
}
}

return 0;
}

最佳答案

您不能期望错误消息总是在提示之前打印。 fork 进程与主程序并行运行。两个程序输出到 stdout 的顺序取决于操作系统调度程序运行进程的方式。

我认为大多数真正的 shell(例如 bash)实际上会在执行 fork() 之前检查主进程中存在的文件。或者,您可以使用 pipe() 并手动重定向输出。然后,您可以在执行提示之前强制刷新整个内容。

关于c - C 中的虚拟 Shell 在关闭外部进程后会出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902836/

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