linux 有名管道使用 mkfifo

简介: linux 有名管道使用 mkfifo

pipe创建的管道只能在具有共同祖先的进程间通信,而mkfifo能在不相关的进程间交换数据。举例来说,匿名管道只能在一个项目文件中通信,类似消息队列;有名管道可在多个程序间通信,类似socket方式。

写端wfifo.c:

#include <stdio.h>
#include <fcntl.h>
#include <error.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main()
{
        char buffer[SIZE];
        int write_fd;
        int ret;
        int len;
        write_fd=open("./swap",O_WRONLY);//打开管道(只写)
        do
        {
                if(write_fd<0)
                {
                        perror("open error");
                        exit(1);
                }
                printf("input data\n");
                fgets(buffer,SIZE,stdin);
                len=strlen(buffer);
                buffer[len-1]='\0';
                ret=write(write_fd,buffer,SIZE);
                if(ret==-1)
                {
                        perror("write error");
                        exit(1);
                }
                printf("send success\n");
        }while(strcmp(buffer,"exit")!=0);
                close(write_fd);
        return 0;
}

读端 rfifo.c

#include <stdio.h>
#include <fcntl.h>
#include <error.h>
#include <stdlib.h>
#define SIZE 128
int main()
{
        char buffer[SIZE];
        int read_fd;
        int ret;
        read_fd=open("./swap",O_RDONLY);
        do
        {
                if(read_fd<0)
                {
                        perror("open error");
                        exit(1);
                }
                ret=read(read_fd,buffer,SIZE);
                if(ret==-1)
                {
                        perror("read error");
                        exit(1);
                }
                printf("the data is:\n");
                printf("%s\n",buffer);
        }while(strcmp(buffer,"exit")!=0);
                close(read_fd);
        return 0;
}

运行效果:


微信图片_20230117212130.png微信图片_20230117212133.png


目录
相关文章
|
1月前
|
Linux Shell
【Linux 进程间通讯 管道】使用Linux管道进行linux进程间通信
【Linux 进程间通讯 管道】使用Linux管道进行linux进程间通信
31 1
|
Unix Linux Windows
【Linux】—— 命名管道详解
【Linux】—— 命名管道详解
|
1月前
|
缓存 Unix Linux
进程间通信之匿名管道和命名管道的理解和实现【Linux】
进程间通信之匿名管道和命名管道的理解和实现【Linux】
|
3月前
|
Linux
Linux有名管道学习——实现两个进程的简单聊天
Linux有名管道学习——实现两个进程的简单聊天
45 0
|
4月前
|
SQL Linux 应用服务中间件
Linux - 管道(|)和grep 命令
Linux - 管道(|)和grep 命令
58 0
|
5月前
|
弹性计算 运维 Shell
Linux加强篇003-管道符、重定向与环境变量
山重水复疑无路,柳暗花明又一村
251 1
|
5月前
|
存储 Unix Linux
|
3天前
|
Linux
【linux进程间通信(一)】匿名管道和命名管道
【linux进程间通信(一)】匿名管道和命名管道
|
1月前
|
消息中间件 Unix Linux
【Linux】—— 匿名管道
【Linux】—— 匿名管道
|
2月前
|
Unix Shell Linux
在Unix/Linux Shell中,管道(`|`)和重定向
在Unix/Linux Shell中,管道(`|`)和重定向
23 1