0

我在这里有一个功能可以阻止 fgets 但是当我在 fgets 之前打印一些东西时它不会阻止。

int exec_command(char *command, char *output_buf, int buf_size)
{
    FILE* pipe = NULL;

    char buffer[BUFFER_SIZE];
    char tmp[SMALL_BUFFER_SIZE];
    unsigned total_read = 0;

    pipe = popen( command, "r");
    if( !pipe )
    {
        //Error
        return -1;
    }

    memset(buffer, 0, sizeof(buffer));
    while( !feof(pipe) ) 
    {
        //printf("reading"); //If I uncomment this fgets doesnt block
        if( fgets(tmp, sizeof(tmp), pipe) != NULL )
        {
            // check that it'll fit:
            size_t len = strlen(tmp);
            if (total_read + len >= sizeof(buffer))
                break;

            // and add it to the big buffer if it fits
            strcat(buffer, tmp);
            total_read += len;
        }
    }
    //Is there anything to copy
    if ( total_read )
    strncpy (output_buf, buffer, buf_size);

    return pclose(pipe);
}

我上面的功能有什么问题吗?

4

2 回答 2

1

这是因为正在写入管道的任何内容都不会刷新其缓冲区。当您打印时,它最终会刷新(虽然不会发生)。当您不打印时,管道实际上并没有被写入,因为它存储在内核缓冲区中直到它被填满,然后内核将写入数据。在写入管道的进程中对管道 fd 调用 fsync 或刷新,以确保刷新内核缓冲区。

于 2013-07-19T19:53:40.390 回答
0

在打印语句中添加一个新行。它(可能)是行缓冲的,并且在遇到换行之前不会打印,您调用fflush.

于 2013-07-19T19:55:58.267 回答