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;
}

执行结果:

相关推荐
Bert.Cai6 分钟前
Linux let命令详解
linux·运维·服务器
枕星而眠9 分钟前
Linux 线程:原理、属性、实战与面试避坑
linux·运维·c语言·面试
晚风予卿云月14 分钟前
【Linux】环境变量概念、作用、配置与修改详解
linux·运维·服务器·环境变量
赏金术士18 分钟前
第六章:UI组件与Material3主题
android·ui·kotlin·compose
r-t-H21 分钟前
从零开始搭建CDH-第十二章
linux·hive·spark·centos·hbase
~黄夫人~34 分钟前
零基础速通|Windows&Linux 常用命令行对照表大全
linux·运维·windows·笔记·备忘录·整理表格
benjiangliu37 分钟前
LINUX系统-17-EXT系列文件系统(二)
linux·运维·服务器
杨云龙UP38 分钟前
Linux 根分区被日志吃满?一次 58G Broker 日志清理实战_2026-05-20
linux·运维·服务器·数据库·hdfs·apache
络合白泽1 小时前
Debian 13 + NVIDIA Optimus 笔记本:从零配置 Wayland Explicit Sync 完整指南
运维·debian
珠海西格电力1 小时前
零碳园区的碳排放指标计算的实操步骤
大数据·运维·人工智能·物联网·能源