Linux C 学习日记 (2) 有名管道

*如何实现通在两个终端的两个进程之间,使用有名管道实现实时通信?one.c和two.c分别运行于两个终端,模拟聊天功能。


one.c two.c 子(写 )--------------fifoabc2------------父(读) 父(读)-------------fifoabc1-------------子(写) one.c two.c

创建一个有名管道是创建一个管道文件,当进程或程序结束后,管道文件依然存在,有名管道可以在不同的程序和没有亲缘关系的进程中使用。

                                 one.c 程序
                                 
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<linux/stat.h>
#include<string.h>
int main()
{
  char s[1024];
  char sb[1024];
  int pid;
  int fd,cn,fd2;
  unlink("fifoabc1");
  unlink("fifoabc2");
  mkfifo("fifoabc1",0666);     //新建 有名管道 fifoabc1
  mkfifo("fifoabc2",0666);     //新建 有名管道 fifoabc2
  pid=fork();   //创建进程
  if(pid>0)
  {
    fd=open("fifoabc1",O_RDONLY);    //以 只读 的方式打开有名管道 fifoabc1
    while((cn=read(fd,sb,sizeof(sb)))>0)   // 使用while 以 换行为结束  
                                           //依次从管道fifoabc1中 读取数据 存入到 sb 中
      printf("%s",sb);      //输出sb中的数据
     close(fd);             //关闭管道
     wait();                //等待子进程
  }
  else if(pid==0)
  {
     fd2=open("fifoabc2",O_WRONLY);        //以 只写 的方式 打开有名管道fifoabc2
    while(1)
   {
     fgets(s,sizeof(s),stdin);          //从  键盘中读取数据到 数组 s 中
     write(fd2,s,sizeof(s));            //从 s 写入数据到 有名管道fifoabc2
   }
   close(fd2);                          //关闭 管道fifoabc2
  }
return 0;
}

分别运行在两个终端

                               two.c程序

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<linux/stat.h>
#include<stdlib.h>
#include<string.h>
int main()
{
   char s[1024];
   char sb[1024];
   int pid;
   int fd,fd2;
   int cn;

 pid=fork();
   if(pid==0)
   {
     fd=open("fifoabc1",O_WRONLY);    //以 只写 的方式打开 管道fifoabc1 
     while(1)
     {
      fgets(sb,sizeof(sb),stdin);     //从 键盘 中读取 数据到 sb 中
      write(fd,sb,sizeof(sb));        //从 sb 中写入数据到管道fifoabc1 中
     }
    close(fd);
    }
   else if(pid>0)
   {
        fd2=open("fifoabc2",O_RDONLY);   //以  只读  的方式 打开管道fifoabc2
         while((cn=read(fd2,s,sizeof(s)))>0)
         printf("%s",s);        
         close(fd2);
    wait();
    }
return 0;
}

猜你喜欢

转载自blog.csdn.net/Black_goat/article/details/83657156
今日推荐