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