linux管道 源码

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

int main()
{
const char *fifo_name = “/tmp/my_fifo”;
int pipe_fd = -1;
int data_fd = -1;
int res = 0;
const int open_mode = O_WRONLY;
int bytes_sent = 0;
char buffer[PIPE_BUF + 1];

if(access(fifo_name, F_OK) == -1)  
{  
    //管道文件不存在  
    //创建命名管道  
    res = mkfifo(fifo_name, 0777);  
    if(res != 0)  
    {  
        fprintf(stderr, "Could not create fifo %s\n", fifo_name);  
        exit(EXIT_FAILURE);  
    }  
}  

printf("Process %d opening FIFO O_WRONLY\n", getpid());  
//以只写阻塞方式打开FIFO文件,以只读方式打开数据文件  
pipe_fd = open(fifo_name, open_mode);  
data_fd = open("Data.txt", O_RDONLY);  
printf("Process %d result %d\n", getpid(), pipe_fd);  

if(pipe_fd != -1)  
{  
    int bytes_read = 0;  
    //向数据文件读取数据  
    bytes_read = read(data_fd, buffer, PIPE_BUF);  
    buffer[bytes_read] = '\0';  
    while(bytes_read > 0)  
    {  
        //向FIFO文件写数据  
        res = write(pipe_fd, buffer, bytes_read);  
        if(res == -1)  
        {  
            fprintf(stderr, "Write error on pipe\n");  
            exit(EXIT_FAILURE);  
        }  
        //累加写的字节数,并继续读取数据  
        bytes_sent += res;  
        bytes_read = read(data_fd, buffer, PIPE_BUF);  
        buffer[bytes_read] = '\0';  
    }  
    close(pipe_fd);  
    close(data_fd);  
}  
else  
    exit(EXIT_FAILURE);  

//printf("Process %d finished\n", getpid());  
printf("Process %d finished, %d bytes write\n", getpid(), bytes_sent);
exit(EXIT_SUCCESS);  

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grimm·

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值