程序功能:创建两个管道,首先读出管道一的数据,再把从管道一中读入的数据写入到管道二中区,这里的select函数采用阻塞形式,也就是首先在程序中实现将数据写入管道一,并通过select函数实现将管道一的数据读出,并写入管道二,接着该程序一直等待用户输入管道一的数据并将其即时读出。
不知道跟系统是不是有关系,在我的机子上运行的不到预期的结果,麻烦各位指点,跑跑这程序看能跑成功不?thanks~~
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int fd[2];
char buf[7];
int i;
int rc;
int maxfd;
fd_set inset1;
fd_set inset2;
struct timeval tv;
/*创建有名管道*/
if ((mkfifo("fifo1", O_CREAT | O_EXCL) < 0)&&(errno != EEXIST))
{
printf("cannot create fifoserver\n");
}
if ((mkfifo("fifo2", O_CREAT | O_EXCL) < 0)&&(errno != EEXIST))
{
printf("cannot create fifoserver\n");
}
/*打开有名管道*/
if ((fd[0] = open("fifo1", O_RDWR | O_NONBLOCK, 0)) < 0)
{
perror("open fifo1");
}
if ((fd[1] = open("fifo2", O_RDWR | O_NONBLOCK, 0)) < 0)
{
perror("open fifo2");
}
if ((rc = write(fd[0], "Hello!\n", 7)))
{
printf("rc = %d\n", rc);
}
lseek(fd[0], 0, SEEK_SET);
maxfd = fd[0] > fd[1] ? fd[0] : fd[1];
/*初始化描述集,并将文件描述符加入到相应的描述集*/
FD_ZERO(&inset1);
FD_SET(fd[0], &inset1);
FD_ZERO(&inset2);
FD_SET(fd[1], &inset2);
/*循环测试该文件描述符是否准备就绪,并调用select函数*/
while (FD_ISSET(fd[0], &inset1) || FD_ISSET(fd[1], &inset2))
{
if (select(maxfd+1, &inset1, &inset2, NULL, NULL) < 0)
{
perror("select");
}
else
{
if (FD_ISSET(fd[0], &inset1))
{
rc = read(fd[0], buf ,7);
if (rc > 0)
{
buf[rc] = '\0';
printf("read : %s\n", buf);
}
else
{
perror("read");
}
}
if (FD_ISSET(fd[1], &inset2))
{
rc = write(fd[1], buf, 7);
if (rc > 0)
{
buf[rc] = '\0';
printf("rc = %d, write: %s\n", rc, buf);
}
else
{
perror("write");
}
}
}
}
exit(0);
}