Linux命名管道实现进程间的通信severclient

    xiaoxiao2022-07-14  141

    1.命名管道

    管道应用的一个限制就是只能在具有共同祖先(具有亲缘关系)的进程间通信。如果我们想在不相关的进程之间交换数据,可以使用FIFO文件来做这项工作,它经常被称为命名管道命名管道是一种特殊类型的文件

    2.匿名管道与命名管道的区别

    匿名管道由pipe函数创建并打开。命名管道由mkfifo函数创建,打开用openFIFO(命名管道)与pipe(匿名管道)之间唯一的区别在它们创建与打开的方式不同,一但这些工作完 成之后,它们具有相同的语义。

    3.命名管道的打开规则

    如果当前打开操作是为读而打开FIFO时O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFOO_NONBLOCK enable:立刻返回成功如果当前打开操作是为写而打开FIFO时O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFOO_NONBLOCK enable:立刻返回失败,错误码为ENXIO

    4.用命名管道实现server&client通信

    github代码

    server代码:

    #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include<string.h> int main() { umask(0); if(mkfifo("mypipe", 0644) < 0){ perror("mkfifo"); exit(-1); } printf("please wait..\n"); int fd = open("mypipe",O_RDONLY); if(fd<0){ perror("open"); exit(-1); } char buf[1024] = {0}; while(1) { size_t s = read(fd,buf,sizeof(buf)-1); if(s>0){ buf[s] = '\0'; printf("client say:%s\n",buf); } else if(s == 0){ printf("client quit\n"); exit(0); } else{ printf("read \n"); } } return 0; }

    client代码:

    #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include<string.h> int main() { int fd = open("mypipe",O_WRONLY); if(fd<0){ perror("open"); exit(-1); } char buf[1024] = {0}; while(1) { printf("please# "); fflush(stdout); scanf("%s",buf); write(fd,buf,strlen(buf)); } return 0; }

    makefile

    .PHONY:all all:client server client:clientPipe.c gcc -o $@ $^ server:serverPipe.c gcc -o $@ $^ .PHONY:clean clean: rm -rf client server mypipe

    5.运行结果

    ps:想要再次运行记得make clean一下, 对mkfifo函数不是很清楚

    最新回复(0)