一、逻辑实现

- 有两个无关的进程A和B;
- 在进程A或B中创建有名管道1和2;
- 在进程A中,以只写方式打开有名管道1,以只读方式打开有名管道2,在while循环里,用gets()获取键盘输入,将输入写管道1,然后读管道2;
- 在进程B中,以只读方式打开有名管道1,以只写方式打开有名管道2,在while循环里,读管道1,然后用gets()获取键盘输入,将输入写管道2;
- 完成通信。
二、代码实现
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
int main(int argc, char const *argv[])
{
time_t timer;
struct tm *tblock;
timer = time(NULL);
int ret = access("fifo1",F_OK);
if(ret==-1)
{
printf("fifo1管道不存,创建管道!\n");
ret = mkfifo("fifo1",0664);
if(ret==-1)
{
perror("mkfifo");
exit(0);
}
}
ret = access("fifo2",F_OK);
if(ret==-1)
{
printf("fifo2管道不存,创建管道!\n");
ret = mkfifo("fifo2",0664);
if(ret==-1)
{
perror("mkfifo");
exit(0);
}
}
int fd1 = open("fifo1",O_WRONLY);
if(fd1==-1)
{
perror("open");
exit(0);
}
int fd2 = open("fifo2",O_RDONLY);
if(fd2==-1)
{
perror("open");
exit(0);
}
char buf[1024]={0};
while(1)
{
fgets(buf,sizeof(buf),stdin);
timer = time(NULL);
tblock = localtime(&timer);
write(fd1,buf,sizeof(buf));
printf("%sA say:%s\n",asctime(tblock),buf);
memset(buf,0,sizeof(buf));
int len = read(fd2,buf,sizeof(buf));
if(len==0)
{
printf("B断开连接!\n");
exit(0);
}
else if(len>0)
{
timer = time(NULL);
tblock = localtime(&timer);
printf("%sB say:%s\n",asctime(tblock),buf);
memset(buf,0,sizeof(buf));
}
}
return 0;
}
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
int main(int argc, char const *argv[])
{
time_t timer;
struct tm *tblock;
int ret = access("fifo1",F_OK);
if(ret==-1)
{
printf("fifo1管道不存,创建管道!\n");
ret = mkfifo("fifo1",0664);
if(ret==-1)
{
perror("mkfifo");
exit(0);
}
}
ret = access("fifo2",F_OK);
if(ret==-1)
{
printf("fifo2管道不存,创建管道!\n");
ret = mkfifo("fifo2",0664);
if(ret==-1)
{
perror("mkfifo");
exit(0);
}
}
int fd1 = open("fifo1",O_RDONLY);
if(fd1==-1)
{
perror("open");
exit(0);
}
int fd2 = open("fifo2",O_WRONLY);
if(fd2==-1)
{
perror("open");
exit(0);
}
char buf[1024] = {0};
while(1)
{
int len = read(fd1,buf,sizeof(buf));
if(len==0)
{
printf("A断开连接\n");
exit(0);
}
else if(len>0)
{
timer = time(NULL);
tblock = localtime(&timer);
printf("%sA say:%s\n",asctime(tblock),buf);
memset(buf,0,sizeof(buf));
}
else if(len==-1)
{
perror("read");
}
fgets(buf,sizeof(buf),stdin);
timer = time(NULL);
tblock = localtime(&timer);
write(fd2,buf,sizeof(buf));
printf("%sB say:%s\n",asctime(tblock),buf);
memset(buf,0,sizeof(buf));
}
return 0;
}
三、效果展示
