程序不会停止在EOF上

non*_*ame -1 c 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] = '\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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:这是修复.谢谢jil

if(getline(&command, &buffsize, stdin)) == -1) {
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

jil*_*jil 6

也许你应该检查EOF然后采取相应的行动.man getline说:

无法读取一行时返回-1(包括文件结束条件)

所以尝试类似的东西:

if (getline(&command, &buffsize, stdin) == -1)
    return 0;
Run Code Online (Sandbox Code Playgroud)