有名管道的介绍及使用

文章介绍了匿名管道和有名管道(FIFO)的概念,强调了有名管道通过路径名关联,允许无亲缘关系的进程通信。通过示例代码展示了如何创建FIFO、以读写方式打开管道以及实现数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 简介

  • 匿名管道,由于没有名字 ,只能进行情缘关系的进程间通信,如父子进程。
  • 有名管道(FIFO),命名管道或FIFO文件。关键点:提供了一个路径名与之关联,以FIFO的文件形式存在于文件系统之中·,打开方式与普通文件的打开方式是一样的,所以即使不存在亲缘关系,只要可以访问路径,就可以通过FIFO通信、

 数据结构:环形队列first in first out先入先出 queue

与匿名管道的不同点:


使用:

/*
创建FIFO文件
1.通过命令 : mkfifo + 名字
2.通过函数 :int mkfifo(const char *pathname,mode_t mode);

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

    int mkfifo(const char *pathname, mode_t mode);
            参数:pathname:管道名称路径
            mode_t:文件的权限,是一个8进制的数
            返回值:成功返回0,失败返回-1,并设置错误号
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
int main(){
    int ret = mkfifo("fifo1",0664);
    if(ret == -1){
        perror("mkfifo");
        exit(0);
    }

}

 实现两个进程之间通信:

write

    //从管道中读取数据
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>

int main(){
    //1.打开管道文件
    int fd = open("test",O_RDONLY);
    if (fd == -1)
    {
        perror("open");
        exit(0);
        /* code */
    }

    //读数据
    while(1){
        char buf[1024] = {0};
        int len = read(fd,buf,sizeof(buf));
        if(len == 0 )
        {
            printf("写端断开连接..\n");
            break;
        }
        printf("recv buf : %s\n",buf);
    }
    

    return 0;
}

read

// 向管道写入数据

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
    //1.判断文件是否存在
    int ret = access("test",F_OK);
    if(ret == -1)
    {
         printf("管道不存在,创建管道\n");
        //2.创建管道文件
        int ret = mkfifo("test",0664);
        if(ret == -1)
        {
        perror("mkfifo");
        exit(0);
        }
    }
    //3.打开管道,以只写的方式
    int fd = open("test",O_WRONLY);
    if (fd == -1)
    {
        perror("open");
        exit(0);
        /* code */
    }
    //数据
    for (int i = 0; i < 100; i++)
    {
        char buf[1024];
        sprintf(buf,"Hello,%d\n",i);
        printf("write data : %s\n",buf);
        write(fd,buf,strlen(buf));
        sleep(1);
        /* code */
    }
    
    close(fd);


     return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值