使用mkfifo阻止读取直到写入

时间:2013-07-17 11:15:06

标签: c file-io mkfifo

gcc (GCC) 4.7.2
c89

我正在使用管道mkfifo。我有一个读者和一个作家。

我希望读者阻止,直到文件中有内容为止。

有一个标志可以设置O_NONBLOCK,用于非阻塞模式。所以默认情况下它应该阻止读取。

写入文件

int main(void)
{
    int fd;
    const char *pipe_file = "../../pipe_file/file";
    const char *pipe_msg = "PIPE Message";

    LOG_INFO("Start writer");

    /* Create the FIFO named pipe with read/write permissions */
    mkfifo(pipe_file, 0666);

    /* Write to the pipe */
    fd = open(pipe_file, O_WRONLY);
    write(fd, pipe_msg, strlen(pipe_msg) + 1);

    LOG_INFO("Terminate writer");

    return 0;
}

从文件中读取

int main(void)
{
    int fd = -1;
    const char *pipe_file = "../../pipe_file/file";
#define BUF_SIZE 1024
    char rd_buffer[BUF_SIZE];

    LOG_INFO("Start reader");

    fd = open(pipe_file, O_RDONLY);

    do {
        memset(rd_buffer, 0, sizeof(rd_buffer));
    /* I WANT IT TO BLOCK HERE, UNTIL THE FILE IS WRITTEN AGAIN */
        read(fd, rd_buffer, sizeof(rd_buffer));
        LOG_INFO("Contents of buffer [ %s ]", rd_buffer);
    /* NO NEED TO SLEEP AS THE FILE WILL DELAY WHEN BLOCKING, I THINK */
    } while(1);

    /* We're done clean up */
    close(fd);
    unlink(pipe_file);

    LOG_INFO("Terminate reader");

    return 0;
}

1 个答案:

答案 0 :(得分:5)

如果fifo的另一端未在写入模式下打开,则read()将立即返回。尝试先运行你的Write程序然后看看。

有关详情,请点击here