C 使用mkfifo在读时阻塞直到写入

C 使用mkfifo在读时阻塞直到写入,c,file-io,mkfifo,C,File Io,Mkfifo,我用的是mkfifo。我有一个读者和一个作家 我希望读取器阻止,直到文件中有内容为止 有一个标志,您可以设置O_NONBLOCK,该标志用于非阻塞模式。因此,默认情况下,它应该在读取时阻塞 写入文件 gcc (GCC) 4.7.2 c89 从文件中读取 int main(void) { int fd; const char *pipe_file = "../../pipe_file/file"; const char *pipe_msg = "PIPE Message"

我用的是mkfifo。我有一个读者和一个作家

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

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

写入文件

gcc (GCC) 4.7.2
c89
从文件中读取

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;
}
如果fifo的另一端在写入模式下未打开,您的
read()
将立即返回。首先尝试运行您的编写程序,然后查看

有关更多信息,请单击如果fifo的另一端在写入模式下未打开,您的
read()
将立即返回。首先尝试运行您的编写程序,然后查看

有关更多信息,请单击

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