使用有名管道实现进程间文件传输(fifo)

解决思路:

        1、创建有名管道文件(mkfifo);

        2、打开文件,读取内容到缓冲区,把缓冲区的内容写道管道(open,read,write);

        3、打开(或新建)文件,读取管道中的内容到缓冲区、把缓冲区的内容写到文件中(open,read,write);

        4、关闭文件,关闭管道文件

1、创建有名管道文件(mkfifo);

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{ 
    int ret = mkfifo("./myfifo",0777);
    if(-1 == ret)
    {
        perror("mkfifo");
        return -1;
    }
    printf("mkfifo success.\n");
    return 0;
} 

    2、打开文件,读取内容到缓冲区,把缓冲区的内容写道管道(open,read,write);

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>

#define SIZE 128

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        printf("pleasr enter %s filename.\n",argv[0]);
        return -1;
    }
    int ret_read = 0;
    int ret_fifo = 0;
    char buf[SIZE] = {0};
    int fd_src = open(argv[1],O_RDONLY);
    if(-1 == fd_src)
    {
        perror("open");
        return -1;
    }
    int fd_fifo = open("./myfifo",O_WRONLY);
    if(-1 == fd_fifo)
    {
        perror("open");
        return -1;
    }
    while(1)
    {
        bzero(buf,sizeof(buf));
        ret_read = read(fd_src,buf,sizeof(buf));
        if(-1 == ret_read)
        {
            perror("read");
            break;
        }
        if(0 == ret_read)
        {
            break;
        }
        write(fd_fifo,buf,ret_read);
    }

    close(fd_src);
    close(fd_fifo);
    return 0;
} 

  3、打开(或新建)文件,读取管道中的内容到缓冲区、把缓冲区的内容写到文件中(open,read,write);

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>

#define SIZE 128
int main(int argc, char *argv[])
{ 
    if(argc < 2)
    {
        printf("pleasr enter %s filename.\n",argv[0]);
        return -1;
    }
    char buf[SIZE] = {0};
    int fd_dest = open(argv[1],O_WRONLY | O_CREAT | O_TRUNC,0777);
    if(-1 == fd_dest)
    {
        perror("open");
        return -1;
    }
    int fd_fifo = open("./myfifo",O_RDONLY);
    if(-1 == fd_fifo)
    {
        perror("open");
        return -1;
    }
    int ret_read_fifo = 0;
    int ret_write_dest = 0;
    while(1)
    {
        bzero(buf,sizeof(buf));
        ret_read_fifo = read(fd_fifo,buf,sizeof(buf));
        if(-1 == ret_read_fifo)
        {
            perror("read");
            break;
        }
        if(0 == ret_read_fifo)
        {
            break;
        }
        write(fd_dest,buf,ret_read_fifo);

    }
    close(fd_dest);
    close(fd_fifo);
    return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值