有名管道总结

      有关无名管道的创建:

       #include <sys/stat.h>

       int mkfifo(const char* pathname,mode_ mode);

       如果是在linux环境下还可以直接在shell终端用mkfifo指令来创建管道文件。

       FIFO常见用途:

      (1)FIFO由shell命令使用以便将数据从一条管道线传送到另一条,为此无需创建中间临时文件。

      (2)FIFO用于客户进程-服务器进程应用程序中,以在客户进程和服务器进程之间传递数据。

        在这里主要讨论第二种用途。(因为第一种用途我也未曾使用过)

       

        先体现用mkfifo创建一个 fifo管道文件,将之作为中转,那么就可以实现两个不相干进程之间的通信了。

        写数据的程序:

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>


int main(int argc,char* argv[])
{
    int fdw = open("./fifo",O_WRONLY);//以写的形式打开fifo的一端
    char buff[128] = {0};
    while(1)
    {
        printf("请输入\n");
        fgets(buff,128,stdin);


        if(strncmp(buff,"end",3)==0)
        {
             break;
        }
        write(fdw,buff,strlen(buff));//数据被直接写入fifo


    }
    close(fdw);
    return 0;


}


读数据的程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>


int main(int argc,char* argv[])
{
    int fdr = open("./fifo",O_RDONLY);//以读的形式打开fifo
    while(1)
    {
        char buff[128]= {0};
        int n = read(fdr,buff,127);//把fifo里面的数据读到buff上
        if(n==0)
        {
             break;
        }
        printf("get buff = %s",buff);
    }
    fflush(stdout);//ensure print succeed
    close(fdr);
    return 0;
}         













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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值