程序不会在 EOF 处停止

Program is not stopping on EOF

目前,当我点击 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] = '[=10=]';

        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;
}

编辑:这是解决方法。感谢 jil

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;