Linux有名管道编程

有名管道可以用于任何两个程序间通信,因为有名字可引用。注意管道都是单向的,因此双方通信需要两个管道。

下面分别是这两个程序代码,同样是Lucy先运行,然后是Peter。

fifoLucy.c

#include<sys/types.h>
#include<sys/stat.h>

#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>

int main()
{
 char write_fifo_name[] = "lucy";
   char read_fifo_name[] = "peter";
   int write_fd, read_fd;
   char buf[256];
   int len;
   struct stat stat_buf;

   int ret = mkfifo(write_fifo_name, S_IRUSR | S_IWUSR);
   if( ret == -1)
 {
    printf("Fail to create FIFO %s: %s",write_fifo_name,strerror(errno));
      exit(-1);
        }

   write_fd = open(write_fifo_name, O_WRONLY);
   if(write_fd == -1)
 {
    printf("Fail to open FIFO %s: %s",write_fifo_name,strerror(errno));
      exit(-1);
        }
       
   while((read_fd = open(read_fifo_name,O_RDONLY)) == -1)
 {
    sleep(1);
        }
     
 while(1)
 {
      printf("Lucy: ");
    fgets(buf, 256, stdin);
      buf[strlen(buf)-1] = '/0';
      if(strncmp(buf,"quit", 4) == 0)
  {
         close(write_fd);
         unlink(write_fifo_name);
         close(read_fd);
         exit(0);
                }
      write(write_fd, buf, strlen(buf));
      len = read(read_fd, buf, 256);
      if( len > 0)
  {
       buf[len] = '/0';
         printf("Peter: %s/n", buf);
                }
        }
}

fifoPeter.c

#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<stdlib.h>

int main(void)
{
 char write_fifo_name[] = "peter";
   char read_fifo_name[] = "lucy";
   int write_fd, read_fd;
   char buf[256];
   int len;

   int ret = mkfifo(write_fifo_name, S_IRUSR | S_IWUSR);
   if( ret == -1)
 {
    printf("Fail to create FIFO %s: %s",write_fifo_name,strerror(errno));
    exit(-1);
    }

   while((read_fd = open(read_fifo_name, O_RDONLY)) == -1)
 {
  sleep(1);
        }
       
   write_fd = open(write_fifo_name, O_WRONLY);
   if(write_fd == -1)
 {
    printf("Fail to open FIFO %s: %s", write_fifo_name, strerror(errno));
      exit(-1);
        }

   while(1)
 {
      len = read(read_fd, buf, 256);
      if(len > 0)
  {
       buf[len] = '/0';
         printf("Lucy: %s/n",buf);
                }
      printf("Peter: ");
      fgets(buf, 256, stdin);
      buf[strlen(buf)-1] = '/0';
      if(strncmp(buf,"quit", 4) == 0)
  {
       close(write_fd);
       unlink(write_fifo_name);
         close(read_fd);
         exit(0);
                }
      write(write_fd, buf, strlen(buf));
        }
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值