先读后写的
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17)
{
perror("mkfifo");
return -1; }
}
printf("mkfifo success\n");
if(mkfifo("./myfifo2", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17)
{
perror("mkfifo");
return -1; }
}
printf("mkfifo2 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)
{
bzero(buf, sizeof(buf));
res = read(fd, buf, sizeof(buf));
if(strcasecmp(buf, "quit") == 0)
break;
if(res < 0)
{
perror("read");
return -1;
}else if(0 == res)
{
printf("对方进程退出\n");
break;
}
printf("read success :%ld : %s\n", res, buf);
printf("请输入>>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd2,buf,sizeof(buf))<0)
{
perror("write");
return -1;
}
printf("write success\n");
if(strcasecmp(buf, "quit") == 0)
break;
}
close(fd);
close(fd2);
return 0;
}
先写再读
#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);
if(mkfifo("./myfifo", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17)
{
perror("mkfifo");
return -1; }
}
printf("mkfifo success\n");
if(mkfifo("./myfifo2", 0777) < 0)
{
printf("errno = %d\n", errno);
if(errno != 17)
{
perror("mkfifo");
return -1; }
}
printf("mkfifo2 success\n");
int fd = open("./myfifo", O_WRONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open writeonly success\n");
int fd2 = open("./myfifo2", O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
printf("open readonly success\n");
char buf[128] = "";
ssize_t res = 0;
while(1)
{
printf("请输入>>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd,buf,sizeof(buf))<0)
{
perror("write");
return -1;
}
printf("write success\n");
if(strcasecmp(buf, "quit") == 0)
break;
bzero(buf, sizeof(buf));
res = read(fd2, buf, sizeof(buf));
if(strcasecmp(buf, "quit") == 0)
break;
if(res < 0)
{
perror("read");
return -1;
}else if(0 == res)
{
printf("对方进程退出\n");
break;
}
printf("read success :%ld : %s\n", res, buf);
}
close(fd);
close(fd2);
return 0;
}