A段代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
umask(0);
//创建有名管道1
if(mkfifo("./myfifo", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17) //如果errno==17代表管道文件已经存在,是合法错误不处理
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
//创建有名管道2
if(mkfifo("./myfifo2", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17) //如果errno==17代表管道文件已经存在,是合法错误不处理
{
perror("mkfifo2");
return -1;
}
}
printf("mkfifo success\n");
//以只读的方式打开有名管道文件
//没有文件创建文件
int fd1= open("./myfifo", O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open readonly success\n");
//以只写的方式打开有名管道文件
int fd= open("./myfifo2", O_WRONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open writeonly success\n");
char buf[128] = "";
ssize_t res = 0;
while(1)
{
printf("B>>说:");
fgets(buf, sizeof(buf), stdin);//从终端拿数据到buf上
buf[strlen(buf)-1] = 0;
if(write(fd1, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
if(strcasecmp(buf,"quit")==0)
break;
printf("write success\n");
//读取数据
bzero(buf, sizeof(buf));//数据清零
res = read(fd, buf, sizeof(buf));//从fd1获取数据
if(res < 0)
{
perror("read");
return -1;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
umask(0);
//创建有名管道1
if(mkfifo("./myfifo", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17) //如果errno==17代表管道文件已经存在,是合法错误不处理
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
//创建有名管道2
if(mkfifo("./myfifo2", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17) //如果errno==17代表管道文件已经存在,是合法错误不处理
{
perror("mkfifo2");
return -1;
}
}
printf("mkfifo success\n");
//以只读的方式打开有名管道文件
//没有文件创建文件
int fd = open("./myfifo", O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open readonly success\n");
//以只写的方式打开有名管道文件
int fd2= open("./myfifo2", O_WRONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open writeonly success\n");
char buf[128] = "";
ssize_t res = 0;
while(1)
{
printf("A>>说:");
fgets(buf, sizeof(buf), stdin);//从终端拿数据到buf上
buf[strlen(buf)-1] = 0;
if(write(fd, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
if(strcasecmp(buf,"quit")==0)
break;
printf("write success\n");
//读取数据
bzero(buf, sizeof(buf));//数据清零
res = read(fd1, buf, sizeof(buf));//从fd1获取数据
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res) //没有写端
{
printf("对方进程退出\n");
break;
}
printf("A接受B收据 :%ld : %s\n", res, buf);
if(strcasecmp(buf,"quit")==0)
break;
}
//关闭文件描述符
close(fd);
//关闭文件描述符
close(fd1);
return 0;
}
B段代码