当前,当我点击 ctrl+d
时,它会不断地一遍又一遍地打印 > ERROR
,直到我暂停程序(ctrl+z
)。我尝试了各种方法来解决这个问题,但它以其他方式破坏了程序。
int main()
{
char *command;
char **parameters;
int status;
size_t buffsize = 0;
while(1)
{
command = NULL;
printf("> ");
getline(&command, &buffsize, stdin);
command[strlen(command)-1] = '\0';
parameters = tokenize(command);
if (!strcmp(command, "exit"))
{
exit(1);
}
if (fork() != 0)
{
waitpid(-1, &status, 0);
}
else
{
status = execvp(command, parameters);
if (status == -1)
{
printf("ERROR\n");
exit(1);
}
}
free(command);
}
return 0;
}
编辑:这是修复方法。谢谢吉尔
if(getline(&command, &buffsize, stdin)) == -1) {
return 0;
}
最佳答案
也许您应该检查 EOF 然后采取相应的行动。 man getline
说:
return -1 on failure to read a line (including end-of-file condition)
所以尝试这样的事情:
if (getline(&command, &buffsize, stdin) == -1)
return 0;
关于c - 程序没有在 EOF 处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756715/