Linux命名管道实现进程间的通信sever/client

1.命名管道

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

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

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

3.命名管道的打开规则

  • 如果当前打开操作是为读而打开FIFO时
  • O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO
  • O_NONBLOCK enable:立刻返回成功
  • 如果当前打开操作是为写而打开FIFO时
  • O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO
  • O_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函数不是很清楚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值