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

执行结果:

相关推荐
aidou13141 小时前
Android中设置Dialog和自定义布局相同高度
android·dialog·弹窗高度·getwindow
氦客1 小时前
UI编程的发展史 : 结合命令式UI和声明式UI
android·compose·声明式ui·ui编程·命令式ui·ui编程发展史·标记语言
BlueBirdssh1 小时前
linux 内核通过 dts 设备树 配置pcie 控制器 各种参数和中断等, 那freeRTOS 是通过直接设置PCIe寄存器吗
linux
小目标一个亿2 小时前
Windows平台Nginx配置web账号密码验证
linux·前端·nginx
实战项目2 小时前
软件测试自动化框架的设计与实现
运维·自动化
Aotman_2 小时前
Element-UI Message Box弹窗 使用$confirm方法自定义模版内容,修改默认样式
linux·运维·前端
Elastic 中国社区官方博客2 小时前
使用 Elastic 中的 OpenTelemetry 为 Nginx 实现端到端分布式追踪的实用指南
大数据·运维·分布式·elasticsearch·搜索引擎·信息可视化·全文检索
独自破碎E2 小时前
配置ssh解决https不稳定的问题
运维·ssh
那些年的笔记3 小时前
Linux屏幕旋转方法
linux·运维·服务器
XiaoHu02073 小时前
Linux网络编程套接字
linux·服务器·网络·git