今天学完管道,利用管道实现单机聊天程序。小白勿喷
*
*思路
:父进程创建子进程,实现多任务。 父进程负责发信息(向 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;
}