友链
程序1:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
// 使用两条有名管道,实现简单的聊天功能
// 进程1
// 以只写方式打开管道1
// 以只读方式打开管道2
// 循环读写数据
/*
while(1) {
获取键盘录入fgets
写管道1
读管道2
}
*/
// 进程2
// 以只读方式打开管道1
// 以只写方式打开管道2
// 循环写读数据
/*
while(1) {
读管道1
获取键盘录入fgets
写管道2
}
*/
// 创建之前首先判断管道文件是否存在
// 使用F_OK宏判断文件访问是否OK
// 测试fifo1和fifo2是否存在,不存在则进行创建
if (access("fifo1", F_OK) == -1)
{
printf("fifo1不存在,进行创建\n");
if (mkfifo("fifo1", 0664) == -1)
{
perror("mkfifo1");
exit(0);
}
}
if (access("fifo2", F_OK) == -1)
{
printf("fifo2不存在,进行创建\n");
if (mkfifo("fifo2", 0664) == -1)
{
perror("mkfifo2");
exit(0);
}
}
// 以只写的方式打开fifo1
int fd1 = open("fifo1", O_WRONLY);
if (fd1 == -1)
{
perror("open");
exit(0);
}
printf("fifo1打开成功\n");
// 以只读的方式打开fifo2
int fd2 = open("fifo2", O_RDONLY);
if (fd2 == -1)
{
perror("open");
exit(0);
}
printf("fifo2打开成功\n");
char buf[128];
// 循环读写数据
while (1)
{
memset(buf, 0, sizeof(buf));
printf("请键入消息>>> %s", buf);
fgets(buf, 128, stdin);
printf("写入数据:%s\n", buf);
if (write(fd1, buf, strlen(buf)) == -1)
{
perror("write");
exit(0);
}
//读数据
memset(buf, 0, sizeof(buf));
if (read(fd2, buf, 128) <= 0)
{
perror("read");
break;
}
printf("收到的内容是: %s\n", buf);
}
close(fd1);
close(fd2);
return 0;
}
程序2:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
// 使用两条有名管道,实现简单的聊天功能
// 进程1
// 以只写方式打开管道1
// 以只读方式打开管道2
// 循环读写数据
/*
while(1) {
获取键盘录入fgets
写管道1
读管道2
}
*/
// 进程2
// 以只读方式打开管道1
// 以只写方式打开管道2
// 循环写读数据
/*
while(1) {
读管道1
获取键盘录入fgets
写管道2
}
*/
// 创建之前首先判断管道文件是否存在
// 使用F_OK宏判断文件访问是否OK
// 测试fifo1和fifo2是否存在,不存在则进行创建
if (access("fifo1", F_OK) == -1)
{
printf("fifo1不存在,进行创建\n");
if (mkfifo("fifo1", 0664) == -1)
{
perror("mkfifo1");
exit(0);
}
}
if (access("fifo2", F_OK) == -1)
{
printf("fifo2不存在,进行创建\n");
if (mkfifo("fifo2", 0664) == -1)
{
perror("mkfifo2");
exit(0);
}
}
// 以只读的方式打开fifo1
int fd1 = open("fifo1", O_RDONLY);
if (fd1 == -1)
{
perror("open fifo1");
exit(0);
}
printf("fifo1打开成功\n");
// 以只写的方式打开fifo2
int fd2 = open("fifo2", O_WRONLY);
if (fd2 == -1)
{
perror("open fifo2");
exit(0);
}
printf("fifo2打开成功\n");
char buf[128];
// 循环读写数据
while (1)
{
//读数据
memset(buf, 0, sizeof(buf));
if (read(fd1, buf, 128) <= 0)
{
perror("read");
break;
}
printf("收到的内容是: %s\n", buf);
memset(buf, 0, sizeof(buf));
printf("请键入消息>>> %s", buf);
fgets(buf, 128, stdin);
printf("写入数据:%s\n", buf);
if (write(fd2, buf, strlen(buf)) == -1)
{
perror("write");
exit(0);
}
}
close(fd1);
close(fd2);
return 0;
}