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

执行结果:

相关推荐
哲伦贼稳妥14 分钟前
职场发展-遇到以下情况请直接准备后手吧
运维·经验分享·其他·职场和发展
带土140 分钟前
10. .out文件
linux
Exquisite.1 小时前
企业高性能web服务器(4)
运维·服务器·前端·网络·mysql
北塔软件1 小时前
北塔方案 | 政府行业IT运维解决方案
运维·it运维·解决方案·政务
STCNXPARM1 小时前
Linux camera之V4L2子系统详解
android·linux·camera·v4l2架构
2501_944525541 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
yueyuexiaokeai11 小时前
linux kernel常用函数整理
linux·c语言
cg_ssh2 小时前
Docker 下启动 Nacos 3.1.1 单机模式
运维·docker·容器
修己xj2 小时前
使用 Docker 部署 SQL Server 并导入 .mdb 文件的完整指南
运维·docker·容器
郝亚军3 小时前
ubuntu-18.04.6-desktop-amd64安装步骤
linux·运维·ubuntu