有名管道FIFO进程间数据传输实例

  紧接着上面一个博客的简单介绍,下面进行一个没有血缘关系的进程间通信的实例,实现文件拷贝传输。

有两个进程,一个主要是fifow进程:读文件Makefile内容,写入管道;另一个进程fifor:读管道内容,写入到Makefile2。

  首先,写端会创建一个管道,然后读取Makefile内容,写入到管道tp中:

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

#include<signal.h>
#define ERR_EXIT(m)
    do
    {
        perror(m);
        exit(EXIT_FAILURE);
    }while(0)  //宏要求一条语句
int main(int argc,char*argv[])
{
    int infd;
    umask(0);
    mkfifo("tp",0644);//创建tp管道
    infd=open("Makefile",O_RDONLY);//打开Makefile
    if(infd==-1)
        ERR_EXIT("open error");
    int outfd;
    outfd=open("tp",O_WRONLY);
    if(outfd==-1)
        ERR_EXIT("open error");
    char buf[1024];
    int n;
    while((n=read(infd,buf,1024))>0)//读Makefile数据
    {
        write(outfd,buf,n);//写入管道
    }
    close(infd);
    close(outfd);    
    return 0;
}

  下面的进程就是读取管道数据,管道中有Makefile的内容,将它们读取出来,然后写入Makefile2,就可以实现拷贝功能了。

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

#include<signal.h>
#define ERR_EXIT(m)
    do
    {
        perror(m);
        exit(EXIT_FAILURE);
    }while(0)  
int main(int argc,char*argv[])
{
    int outfd;
    umask(0);
    outfd=open("Makefile2",O_WRONLY|O_CREAT|O_TRUNC,0644);//打开Makefile
    if(outfd==-1)
        ERR_EXIT("open error");
    int infd;//读取管道数据。
    infd=open("tp",O_RDONLY);
    if(infd==-1)
        ERR_EXIT("open error");
    char buf[1024];
    int n;
    while((n=read(infd,buf,1024))>0)//读管道数据
    {
        write(outfd,buf,n);//写入Makefile2
    }
    close(infd);
    close(outfd);    
    unlink("tp");
    return 0;
}
原文地址:https://www.cnblogs.com/wsw-seu/p/8399612.html