gpt4 book ai didi

c - 输入 EOF 时 Shell 无限循环 C

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:14 43 4
gpt4 key购买 nike

我是一名新的 C 程序员,正在尝试创建自己的 shell。 shell 本身运行良好并正确处理我的命令,但是当用户输入 EOF 字符作为命令行输入时,我的 shell 只是无限循环。我的代码以及我已经尝试过的代码都发布在下面(我也是使用 GDB 和 Valgrind 的新手,但似乎都没有帮助我找到问题所在)。

我已经尝试过的:

  1. 下面的当前实现 try catch getline 的返回值并处理它返回 -1 的情况(当读取 EOF 时)。然而,这只会导致 shell 无限循环提示
  2. 我将我的函数调用完全替换为:

    if (fgets(command_line, MAX_CANON, stdin) == NULL) {
    printf("\nTo quit, please use the exit command: exit.\n");
    }

据我所知,上述替换应该处理用户输入的 EOF 字符。然而,这种使用 fgets 的实现也会导致无限的命令提示符循环。

下面是我当前的实现,在上面的 #1 中提到:

在 main 中调用函数以读取用户的输入:

char *read_command_line(void)
{
//Declare an integer to hold the length of the string, a line to hold our output, and a variable getline can use to hold the generated buffer
int len;
char *line = NULL;
ssize_t bufsize = 0;

//Get the line from stdin
int retval = getline(&line, &bufsize, stdin);

if(retval == -1)
{
line = NULL;
return line;
}

//Determine the length of the line and set a null terminating byte to end the string and get rid of the trailing return
len = strlen(line);
line[len - 1] = '\0';

//Finally return the read in line
return line;
}

我的 shell while 循环的开头是读入的行:

//BEGIN SHELL
while (go)
{
//Signals are handled in the main.c
//Print the prompt
char cwd_loop[max_buf_size];
getcwd(cwd_loop, sizeof(cwd_loop));
printf("\n%s [%s]:> ", prompt_prefix, cwd_loop);

commandline = read_command_line();

if(commandline == NULL)
{
continue;
}

最佳答案

来自你的代码

commandline = read_command_line();  

if(commandline == NULL)
{
continue;
}

如果 read_command_line 返回一个空指针,如果出现像 EOF 这样的错误,它就会返回一个空指针,然后您继续循环,让它迭代再次。这次 read_command_line再次返回一个空指针,您将永远这样继续下去。

如果 read_command_line 返回空指针,您应该break 退出循环。

关于c - 输入 EOF 时 Shell 无限循环 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52579805/

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