学习小练习
通过有名管道的方式实现全双工通信,以此来实现两个程序间的简略聊天。
思路
Linux系统下有名管道实现双方互传
可以在两个程序中各定义一个字符数组负责接收和上传管道中的内容,每个程序中分别创建一个父进程和子进程,一个负责实现终端输入到管道1,一个进程负责实现从管道中读取到内容并打印到终端。

代码
文件1
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char buf[32] = "";
if (mkfifo("./1fifo", 0666) != 0) //用户1发送用户2接收
{
if (errno == EEXIST)
{
printf("fifo file exist\n");
}
else
{
perror("fifo error");
return -1;
}
}
if (mkfifo("./2fifo", 0666) != 0)
{
if (errno == EEXIST)
{
printf("fifo file exist\n");
}
else
{
perror("fifo error");
return -1;
}
}
pid_t pid = fork();
if (pid < 0)
{
perror("pid error");
return -1;
}
else if (pid == 0) //子进程发送
{
int fd = open("./1fifo", O_WRONLY);
if (fd < 0)
{
perror("open error");
return -1;
}
while (1)
{
fgets(buf, sizeof(buf), stdin);
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
write(fd, buf, strlen(buf));
printf("用户1已发送的消息:%s\n", buf);
if (strncmp(buf, "quit", 4) == 0)
{
break;
}
}
close(fd);
exit(0);
}
else //父进程接收
{
int fp = open("./2fifo", O_RDONLY);
if (fp < 0)
{
perror("open error");
return -1;
}
while (1)
{
memset(buf, 0, sizeof(buf));
read(fp, buf, sizeof(buf) - 1);
printf("用户1接收的消息:%s\n", buf);
if (strncmp(buf, "quit", 4) == 0)
{
break;
}
}
wait(NULL);
close(fp);
}
return 0;
}
文件2
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char buf[32] = "";
if (mkfifo("./1fifo", 0666) != 0) //用户1发送用户2接收
{
if (errno == EEXIST)
{
printf("fifo file exist\n");
}
else
{
perror("fifo error");
return -1;
}
}
if (mkfifo("./2fifo", 0666) != 0)
{
if (errno == EEXIST)
{
printf("fifo file exist\n");
}
else
{
perror("fifo error");
return -1;
}
}
pid_t pid = fork();
if (pid < 0)
{
perror("pid error");
return -1;
}
else if (pid == 0) //子进程接收
{
int fd = open("./1fifo", O_RDONLY);
if (fd<0)
{
perror("open error");
return -1;
}
while (1)
{
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf)-1);
printf("用户2接收的消息:%s\n",buf);
if (strncmp(buf,"quit",4)==0)
{
break;
}
}
close(fd);
exit(0);
}
else //父进程发送
{
int fp=open("./2fifo",O_WRONLY);
if (fp<0)
{
perror("open error");
return -1;
}
while (1)
{
fgets(buf,sizeof(buf),stdin);
if(buf[strlen(buf)-1]=='\n')
buf[strlen(buf)-1]='\0';
write(fp,buf,strlen(buf));
printf("用户2发送的消息:%s\n",buf);
if (strncmp(buf,"quit",4)==0)
{
break;
}
}
wait(NULL);
close(fp);
}
return 0;
}