有名管道

write.c

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <limits.h>  
#include <sys/types.h>  
#include <sys/stat.h>  

#define FIFO_NAME "/dev/my_fifo"  
#define BUFFER_SIZE 20
#define TEN_MEG (100)  
  
int main()  
{  
    int pipe_fd;  
    int res;  
    int open_mode = O_WRONLY;  
    int i=0;
    int bytes = 0;  
    char buffer[BUFFER_SIZE];  
  
    if (access(FIFO_NAME, F_OK) == -1)  
    {  
        res = mkfifo(FIFO_NAME, 0777);  
        if (res != 0)  
        {  
            fprintf(stderr, "Could not create fifo %s
", FIFO_NAME);  
            exit(EXIT_FAILURE);  
        }  
    }  
  
  //在这里会阻塞,直到read的open
    pipe_fd = open(FIFO_NAME, open_mode);  
    if (pipe_fd != -1)  
    {  
        
        while (bytes < TEN_MEG)  
        {  
            sleep(1);
            i++;
            memset(buffer, i, sizeof(buffer));
            res = write(pipe_fd, buffer, BUFFER_SIZE);  
            if (res == -1)  
            {  
                fprintf(stderr, "Write error on pipe
");  
                exit(EXIT_FAILURE);  
            }  
            bytes += res;  
        }  
        close(pipe_fd);  
    }  
    else  
    {  
        exit(EXIT_FAILURE);  
    }  
  
    printf("write: finish bytes=%d
", bytes);  
    exit(EXIT_SUCCESS);  
}

read.c

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <limits.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
  
  
#define FIFO_NAME "/dev/my_fifo"  
#define BUFFER_SIZE 1  
  
int main()  
{  
    int pipe_fd;  
    int res;  
  
    int open_mode = O_RDONLY;  
    char buffer[BUFFER_SIZE];  
    int bytes = 0;  
  
    memset(buffer, '', sizeof(buffer));  
  
  //在这里会阻塞,直到write的open
    pipe_fd = open(FIFO_NAME, open_mode);  
if (pipe_fd != -1)  
    {  
        do{  
            memset(buffer,0x0, sizeof(buffer));
       //当无数据可读的时候会阻塞在这里 res
= read(pipe_fd, buffer, BUFFER_SIZE); bytes += res; }while(1); close(pipe_fd); } else { exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
原文地址:https://www.cnblogs.com/maogefff/p/8662742.html