foggia2004

fifo read

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

#define FIFO    "/tmp/myfifo"

int main(int argc,char *argv[])
{
    int fd;         //file description
    char buf_r[50];    //read buffer
    
    if((mkfifo(FIFO,O_CREAT|O_EXCL|0666)<0) && (errno!=EEXIST))
    {
        printf("Create FIFO fail!\n");
    }

    
    fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
    if(fd==-1)
    {
        printf("Open the FIFO fail!\n");
        exit(0);
    }

    memset(buf_r,0,sizeof(buf_r));
    while(1)
    {
        memset(buf_r,'\0',sizeof(buf_r));
        if(read(fd,buf_r,50)<0)
        {
            if(errno==EAGAIN)
                printf("There are no data in FIFO!\n");
        }
        if(buf_r[0]!='\0')
            printf("Reading data from FIFO are: %s\n",buf_r);
        sleep(1);
    }

    return 0;
}

 

posted on 2016-05-20 11:51  foggia2004  阅读(174)  评论(0)    收藏  举报

导航