linux ipc 有名管道

介绍

   1、有名管道是linux系统下的一种ipc通信机制。

   2、命名管道也被称为FIFO文件,是一种特殊的文件。

作用

  1、有名管道是相对于无名管道而产生的,我们知道无名管道只能亲信进程间可以使用,而有名管道在互不相干的两个进程之间可以实现数据交换。

关键方法

 int mkfifo(const char *filename, mode_t  mode)
 
 参数:filename 有名管道文件名(包括路径);mode 权限(读写0666)
 
 注意点:
   
    以O_WRONLY打开管道,读阻塞
   
    以O_RDWR打开管道,当管道中没有数据,读阻塞
   
   //当进程用open打开有名管道用只读方式打开的话,则返回的文件描述符就代表管道的读端

用列

读取输入写入有名管道中

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
    char buf[50] = {0};
    if(mkfifo("./nameFifo",0777) != 0 ) //创建有名管道
    {
        if(errno == EEXIST)
        {
            printf("File exists\n");
        }
        else
        {
            perror("mkfifo fail ");
            exit(1);
        }
    }

    int fd_fifo;
    fd_fifo = open("./nameFifo",O_WRONLY);//只写方式打开,管道描述符
    if(fd_fifo < 0)
    {
        perror("open fifo fail: ");
        exit(1);
    }

    int c ,rc;
    while((c = getchar()) > 0)
    {
        rc = write(fd_fifo, &c, 1);
        if(rc == -1)
        {
            printf("write error\n");
            close(fd_fifo);//关掉写
            exit(1);
        }
    }
    close(fd_fifo);
    return 0;
}

读取有名管道写入输出中

/* 功能:实现在有名管道中读取数据,写到文件中
 * */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

int main(int argc, const char *argv[])
{
    char buf[20];
    memset(buf,0,sizeof(buf)*20);
    if(mkfifo("./nameFifo",0777) != 0 ) //创建有名管道
    {
        if(errno == EEXIST) //有名管道存在的情况
        {
            printf("File exists\n");
        }
        else
        {
            perror("mkfifo fail ");
            exit(1);
        }
    }
    
    int fd_fifo;  //此处fd_r是指有名管道,在有名管道中读取数据,写到文件中

    fd_fifo = open("./nameFifo",O_RDONLY);//读方式打开
    if(fd_fifo < 0)
    {
        perror("open fifo fail: ");
        exit(1);
    }

    //fifo 中循环读取数据,然后写到文件中
    int rc;
    while(1)
    {
        rc = read(fd_fifo,buf,20); //读有名管道内容,返回读取多少个数据
        if (rc <= 0 ) {
            close(fd_fifo);//关掉写
            exit(1);
        }
        printf("read context : %s", buf);
        memset(buf,0,sizeof(buf)*20);

    }
    close(fd_fifo);
    return 0;
}

执行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值