linux多进程基础(5):有名管道(fifo)

本文介绍了Linux系统中的有名管道(FIFO)概念,包括如何使用mkfifo函数创建管道以及open函数打开管道。通过创建write.cpp和read.cpp示例,展示了两个无关进程如何通过有名管道成功进行通信。
摘要由CSDN通过智能技术生成

在linux多进程基础(4)中我们一起学习了无名管道,使用无名管道可以实现父子进程间的通信.但是不知大家有无考虑过,如果两个进程之间毫无相关,那么就无法通信了吗?答案肯定是否定的,为了实现任意两个毫无关系的进程的通信,引入了有名管道的概念.

有名管道(FIFO)是一种特殊的文件类型,可以在不相关的进程之间进行通信。与无名管道不同,有名管道有一个路径名与之关联,因此可以在文件系统中访问。在Linux中,多进程可以通过有名管道进行通信。

1.有名管道

要使用有名管道,需要了解两个相关函数:

(1)mkfifo函数

mkfifo函数用于创建一个命名管道(FIFO),定义如下:

#include <sys/types.h>  
#include <sys/stat.h>  
#include <stdio.h>  
int mkfifo(const char *path, mode_t mode);

其中,path为指定命名管道的路径名,mode为指定管道的权限模式,类似于文件权限的模式。通常使用0666表示所有用户都具有读写权限。

(2)open函数

open函数用于打开或创建文件,并返回一个文件描述符。定义如下:

#include <fcntl.h>  
int open(const char *pathname, int flags);

其中pathname为指定要打开或创建的文件的路径名.

flags为指定文件的打开方式:

  • O_RDONLY:以只读方式打开文件。
  • O_WRONLY:以只写方式打开文件。
  • O_RDWR:以读写方式打开文件。
  • O_CREAT:如果文件不存在,则创建该文件。需要提供第三个参数mode来指定文件的权限模式。
  • O_TRUNC:如果文件已经存在,则将其截断为零长度。
  • O_APPEND:将数据追加到文件末尾。

 2.举例

 我们创建一个fifo文件,展示mkfifo函数的用法,代码如下:

#include <sys/types.h>  
#include <sys/stat.h>  
#include <stdio.h>  
int main(){
    int a= mkfifo("myfifo",0666);
    if (a==-1){
        perror("有名管道创建失败!");
    }
}

运行可以看出产生了一个fifo类型的文件:

 为了模拟两个不相关的进程之间进行通信,我们创建了两个cpp文件代表两个不相关的进程,分别是write.cpp和read.cpp.

write.cpp

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

int main(){
    int fifo_open=open("fifo",O_WRONLY);
    if(fifo_open==-1){
        perror("管道打开错误");
        exit(0);
    }

    for(int i=0;i<50;i++){
        char message[1024];
        sprintf(message,"hello,%d\n",i);   //将字符串 "hello," 和整数 i 的值(后面跟着一个换行符)写入到 message 字符串中。
        printf("write data:%s\n",message);
        int a =write(fifo_open,message,sizeof(message));
        if(a==0){
            perror("断开链接,写入失败!");
        } 
        sleep(1);
    }

}

read.cpp

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

int main(){
    int fifo_open=open("fifo",O_RDONLY);
    if(fifo_open==-1){
        perror("管道打开错误");
        return 1;
    }
    
    while(1){
        char message[1024]={0};
        int a =read(fifo_open,message,sizeof(message));
        if(a==0){
            perror("断开链接,读入失败!");
            return 1;
        }
        printf("read data:%s\n",message);
        sleep(1);
    }

}

打开两个终端,分别编译运行两个cpp,得到结果如下:

 可以看出,两个进程成功通信.

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值