Linux系统编程——进程通信之有名管道

Linux系统编程------进程通信之有名管道

有名管道

有名管道可以使互不相关的两个进程互相通信。有名管道可以通过路径名,并且在文件系统中可见。进程通过为文件IO操作有名管道。不支持lseek()操作,遵循先进先出原则。

mkfifo

c 复制代码
int mkfifo(const char* filename, mode_t mode);

功能:创建管道文件。

filename:要创建的管道。

mode:管道的访问权限,一般用八进制数表示。

返回值:成功返回0,出错返回-1

实例:通过管道进行多进程输入输出

代码:

read.c

c 复制代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int fd;
        char buf[32];
        if (mkfifo("./fifo", 0666) < 0) {
                if (errno == EEXIST) {
                        printf("exist\n");

                } else {
                        perror("mkfifo err");
                        return -1;

                }

        }
        fd = open("./fifo", O_WRONLY);
        if (fd < 0 ) {
                perror("open failed:");
                return -1;

        }
        while(1) {
                fgets(buf, sizeof(buf), stdin);
                write(fd, buf,strlen(buf));
                if (strncmp(buf, "quit", 4) == 0)
                        break;
        }

        close(fd);
        return 0;
}

write.c

c 复制代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int fd;
        int dest_fd;
        char buf[32];
        if (mkfifo("./fifo", 0666) < 0) {
                if (errno == EEXIST) {
                        printf("exist\n");

                } else {
                        perror("mkfifo err");
                        return -1;

                }

        }
        fd = open("./fifo", O_RDONLY);
        if (fd < 0 ) {
                perror("open failed:");
                return -1;
        }

        while(1) {
                read(fd, buf, sizeof(buf));
                if(strncmp(buf, "quit",4) == 0)
                        break;
                printf("buf:%s", buf);
        }

        close(fd);
        return 0;
}

执行结果:

相关推荐
高梦轩27 分钟前
MySQL高可用
android·运维·数据库
hsjcjh4 小时前
Nodemailer使用教程:在Node.js中发送电子邮件
linux·运维·node.js
RATi GORI4 小时前
MySQL中的CASE WHEN语句:用法、示例与解析
android·数据库·mysql
没有梦想的咸鱼185-1037-16635 小时前
北斗高精度数据解算:破解城市峡谷/长基线/无网区难题,从毫米级定位到自动化交付——(GAMIT/GLOBK底层核心解算技术方法)
运维·arcgis·数据分析·自动化
不怕犯错,就怕不做5 小时前
linux 如何查看自己的帐号密码及samba的帐号和密码
linux·运维·服务器
实在智能RPA5 小时前
Agent 在物流行业能实现哪些自动化?——深度拆解 AI Agent 驱动的智慧物流新范式
运维·人工智能·ai·自动化
地下核武5 小时前
Ubuntu 24.04 在线安装 Qt 6.10.2 后 Qt Creator 无法启动问题记录与解决
linux·qt·ubuntu
MoFe15 小时前
【Mysql】创建IP授权用户并授权
android
张3235 小时前
Linux 启动过程
linux·运维
三万棵雪松5 小时前
【Linux 物联网网关主控系统-Linux主控部分(二)】
linux·嵌入式linux