質問

gcc (GCC) 4.7.2
c89

I am using pipes mkfifo. I have a reader and a writer.

I want the reader to block until there is something in the file.

There is a flag you can set O_NONBLOCK which is for non-blocking mode. So by default it should block on the read.

Writing to the file

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

Reading from the file

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;
}
役に立ちましたか?

解決

Your read() will return immediately in case of the other end of the fifo is not open in the write mode. Try to run your Write program first and see.

For more information please click here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top