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

执行结果:

相关推荐
小北方城市网19 小时前
第 6 课:Vue 3 工程化与项目部署实战 —— 从本地开发到线上发布
大数据·运维·前端·ai
旖旎夜光20 小时前
Linux(3)(下)
linux·学习
小鹿学程序20 小时前
任务一-1.子任务一:基础环境准备
linux·bigdata
Nautiluss21 小时前
一起玩XVF3800麦克风阵列(十)
linux·人工智能·python·音频·语音识别·实时音视频·dsp开发
悲喜自渡72121 小时前
Python 编程(gem5 )
java·linux·开发语言
不怕犯错,就怕不做21 小时前
RK3562 +RK817的dts布尔属性解析(uboot基础知识)
linux·驱动开发·嵌入式硬件
记得记得就15121 小时前
docker作业
运维·docker·容器
yangpipi-21 小时前
《C++并发编程实战》第5章 C++内存模型和原子操作
android·java·c++
运维行者_1 天前
OPM 与传统管理工具的区别,在网络修复与自动化运维方面的优势在哪里?
运维·服务器·开发语言·网络·自动化·php·ssl
HaSaKing_7211 天前
EMQX 多机集群部署完整实践(Docker + 社区版 5.8.8)
运维·docker·容器·emqx