今天学完管道,利用管道实现单机聊天程序。小白勿喷

今天学完管道,利用管道实现单机聊天程序。小白勿喷
*

*思路

:父进程创建子进程,实现多任务。 父进程负责发信息(向 FIFO 里写数据),子进程负责接收信息( 从 FIFO 里读数据)。
**

流程图

在这里插入图片描述在这里插入图片描述

代码

//lucy端
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
  pid_t pid;
  int fd;
  int fd1;
  int n;
  char chat[100];
  char chat1[100];
  char buf1[100];
  printf("hello,I am lucy!\n");
  
  
  mkfifo("L_P",0777);
  fd=open("./L_P",O_WRONLY);//创建只写的管道
  if(fd<0)
  {
  perror("open");
  return 0;
  }
  
  
  mkfifo("P_L",0777);
  fd1=open("./P_L",O_RDONLY);//创建只读的管道
  if(fd1<0)
  {
  perror("open");
  return 0;
  }
  
  pid=fork();//创建子进程
  if(pid<0)
  perror("fork");
  if(pid==0)
  {
    
   
    //fflush(stdout);
    while(1)
    {
    printf("lucy:");
    fgets(chat,99,stdin);//从屏幕中获取键盘输入
    write(fd,chat,99);//写入管道
    }
    
  }
  else
  {
    while(1)
    {
    n=read(fd1,buf1,99);//从另一个管道中读出数据
    if(n!=-1)
    {
    printf("\rpeter:%s",buf1);
    printf("lucy:");
    fflush(stdout);
    }
    }

  }

close(fd);
close(fd1);


  return 0;
}
//peter端
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>

int main()
{
  int fd;
  int fd1;
  char chat[100];
  char chat1[100];
  char buf[100];
  pid_t pid;
  int n;
  //char string[100];
  
  
  printf("hello,I am peter!\n");
 
 
   mkfifo("L_P",0777);
  fd=open("./L_P",O_RDONLY);//创建只写的管道
  if(fd<0)
  {
  perror("open");
  return 0;
  }
  
   mkfifo("P_L",0777);
  fd1=open("./P_L",O_WRONLY);//创建只读的管道
  if(fd1<0)
  {
  perror("open");
  return 0;
  }
  
  pid=fork();
  if(pid<0)
  perror("fork");
  
  if(pid==0)
  {

    
    //fflush(stdout);
    while(1)
    {
    printf("peter:");
    fgets(chat1,99,stdin);
    write(fd1,chat1,99);
    }
  }
  else
  {
    while(1)
    {
    n=read(fd,buf,99);
    if(n!=-1)
    {
    printf("\rlucy:%s",buf);
    printf("peter:");
    fflush(stdout);
    }
  }

}
close(fd);
close(fd1);

  return 0;
}

运行结果

在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值