命名管道(有名管道)的使用-例程序

命名管道的读取端  Fifo_read.c

#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define FIFO "/tmp/myfifo" //命名管道设备名称

int main(int argc,char** argv)
{
        int fd;
        char r_buf[100];
        int nread;

        if((mkfifo(FIFO,O_CREAT|O_EXCL|O_RDWR)<0) && (errno!=EEXIST))   //建立命名管道,判断管道是否建立成功
                printf("cannot creat fifo \n");
        printf("prepareing for reading bytes . .\n");

        fd=open(FIFO,O_RDONLY,0);                                //打开命名管道
        if(fd<0){
                printf("fifo open error\n");
                exit(1);
        }
        while(1){
                memset(r_buf,0,sizeof(r_buf));
                if((nread=read(fd,r_buf,10))==-1){                //将命名管道里的内容读取到r_buf[]中
                        if(errno==EAGAIN)
                                printf("no data yet\n");
                }

                printf("read len=%d str=%s from FIFO,nread=%d\n",strlen(r_buf),r_buf,nread);
                sleep(1);
        }

        close(fd);
        return 0;
}
~   

命名管道写入端 Fifo_write.c

#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define FIFO "/tmp/myfifo" //命名管道设备名称

int main(int argc,char** argv)
{
        int fd;
        char w_buf[100];
        char ww_buf[1024];
        int nwrite;

        if(argc==1){
                printf("arg error\n");
                exit(0);
        }
        if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))   //打开或创建命名管道
                printf("cannot creat fifo \n");
        printf("prepareing for writing bytes . .\n");

        fd=open(FIFO,O_WRONLY,0);                                //打开命名管道这个文件
        if(fd<0){
                if(errno==ENXIO)
                        printf("open error; no reading process\n");
                printf("fifo open error\n");
                exit(1);
        }

/*
        for(i=0;i<(argv-1);i++){
                printf("%d++",i);
                strcpy(w_buf,argv[i+1]);
                printf("%d++",i);
                strcpy(ww_buf,w_buf);
        }
*/
        strcpy(w_buf,argv[1]);                    //将命令行的第一个参数出个数组,将数组的内容写入到命名管道中
        while(1){
                if((nwrite=write(fd,w_buf,strlen(w_buf)))==-1){
                        if(errno==EAGAIN)
                                printf("the FIFO has not been read yet.\n");
                }else
                        printf("write %s to the FIFO\n",w_buf);
                sleep(1);
        }
        close(fd);

        return 0;
}
~  

在命令行输入 ./Fifo_read 

新建一个终端,在新建的终端中输入  ./Fifo_write hello_Fifo

这样就可以实现在两个不是父子进程关系的进程中同时使用命名管道,并实现命名管道的读写。

猜你喜欢

转载自blog.csdn.net/cxyzyywoaini/article/details/87464220
今日推荐