系统编程之金城通信 fifo

来源:互联网 发布:南佛罗里达大学 知乎 编辑:程序博客网 时间:2024/04/27 15:21

 

/*fifo_read.c*/

#include<sys/types.h>

#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"
int main(int argc, char ** argv)
{
    char buf_r[100];
    int fd=-1;
    int nread;
    printf("Preparing for reading bytes...\n");
    memset(buf_r,0,sizeof(buf_r));
    /*打开管道*/
    fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
    if(fd==-1)
    {
        perror("open\n");
        exit(1);
    }
    while(1)
    {
        memset(buf_r,0,sizeof(buf_r));
        if((nread=read(fd, buf_r, 100))== -1)
        {
            if(errno == EAGAIN)
                printf("no data yet\n");
        }
        printf("read %s from FIFO\n",buf_r);
        sleep(1);
    }
    close(fd);//关闭管道
    pause();//暂停,等待信号
    unlink(FIFO);//删除文件
}
 
 
/*fifo_write.c*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER "/tmp/myfifo"
int main(int argc, char ** argv)
{
    int fd;
    char w_buf[100];
    int nwrite,sum=0;
    /*创建有名管道 mkfifo()除第一次成功外,其余都失败 error 为EEXIST*/
    if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL|O_RDWR)<0) && (errno != EEXIST))
    {
        printf("cannot create fifoserver\n");
    }
    /*打开管道*/
    fd=open(FIFO_SERVER,O_RDWR|O_NONBLOCK,0);
    if(fd == -1)
    {
        perror("open\n");
        exit(1);
    }
    /*入参检测*/
    if(argc == 1)
    {
        printf("Please send something\n ");
        exit(-1);
    }
    strcpy(w_buf,argv[1]);
    /*向管道写入数据*/
    if((nwrite=write(fd,w_buf,100))==-1)
    {
        if(errno == EAGAIN)
            printf("The FIFO has not been read yet.Please try later\n");
    }
    else
        printf("Write %s to the FIFO \n",w_buf);
    sum+=sizeof(argv[1]);
        printf("You have written %d bytes to myfifo\n",sum);
        close(fd);//关闭管道
        return 0;
}