进程通信—命名管道

     今天和大家分享一下进程通信—命名管道。

        命名管道和匿名管道的性质基本一致(上篇博客有详细描述,不在此再做说明),区别是命名管道可满足任意两个进程之间的通信。

        接着,说明命名管道任意两个进程的通信过程:

   a.由进程A利用mkfifo建立管道文件mypipe.

   b.进程A以读(或者写)的方式打开管道文件mypipe,一直读(或者写)。

   c.进程B以写(或者读)的方式打开管道文件mypipe,一直写(或者读)。

   d.当写(或者读)的任意一方进程退出(关闭管道文件),另外一方进程接受到相应信号后退出。


  代码运行截图:

 

Serve.c

 

client.c

 

Makefile

  运行界面如下:

 


元代码如下:

namepipe.h

 #include<stdio.h>
 #include<unistd.h>
 #include<sys/types.h>
 #include<sys/stat.h>
 #include<fcntl.h>
 #include<stdlib.h>
   
   int main(){
       umask(0);
      if(mkfifo("./mypipe", S_IFIFO|0666)<0){
          perror("mkfifo error!\n");
          exit(-1);
      }
  
          int fd = open("./mypipe", O_RDONLY);
          if(fd<0){
              perror("open wronng!");
              exit(-2);
          }
  
          char buf[1024];
          while(1){
          buf[0] = 0;
          ssize_t s = read(fd, buf, sizeof(buf)-1);
          if(s>0){
              buf[s] = 0;
              printf("parent:%s\n", buf);
             }
           else if(s == 0){//child quit,so parent will quit
               close(fd);
               printf("child quit,so parent will quit!\n");
               break;
              }
          else{//wrong
                 close(fd);
                 exit(3);
             }
            }
      return 0;
  }

client.c

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

Makefile

 .PHONY:all
   all:client serve
   
  client:client.c
       gcc -o client client.c
  serve:namepipe.c
       gcc -o serve namepipe.c
   
  .PHONY:clean
  clean:
      rm -f client serve mypipe


分享如上,望共同进步!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值