#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#include <sys/select.h>
#define OPEN_FLAGS (O_RDWR | O_NOCTTY /*| O_NONBLOCK*/)
int main (int argc, char *argv[])
{
int fd1 = -1;
int fd2 = -1;
int ret = 0;
fd_set rset = {0};
fd_set wset = {0};
char buf[128]= "chen liang zhen";
/*打开串口*/
fd1 = open("./fifo1", OPEN_FLAGS);
fd2 = open("./fifo2", OPEN_FLAGS);
if (-1 == fd1)
{
printf("open fifo1 failed!\n");
ret = -1;
goto _out;
}
if (-1 == fd2)
{
printf("open fifo2 failed!\n");
ret = -1;
goto _out;
}
while(1)
{
FD_ZERO(&rset);
FD_SET(fd1, &rset);
FD_ZERO(&wset);
FD_SET(fd2, &wset);
//printf("select now....\n");
ret = select(fd2 + 1, &rset, &wset, NULL, NULL);
if ((-1 == ret) && (EINTR == errno))
continue;
if (-1 == ret)
{
perror("select failed");
goto _out;
}
lseek(fd1, 0, SEEK_SET);
if(0 == strcmp("read", argv[1]))
{
if (FD_ISSET(fd1, &rset))
{
// memset(buf, 0, sizeof(buf));
if(0 == strcmp("read", argv[1]))
printf("read now...\n");
while((-1 == (ret = read(fd1, buf, sizeof(buf))))
&& (errno == EINTR));
if (-1 == ret)
{
perror("read failed");
goto _out;
}
printf("read from comm(%d): %s\n", ret, buf);
}
if(0 == strcmp("write", argv[1]))
{
if (FD_ISSET(fd2, &wset))/*串口可写*/
{
while((-1 == (ret = write(fd2, buf, sizeof(buf)))) && (EINTR == errno));
if (-1 == ret)
{
perror("write failed");
goto _out;
}
printf("write to comm(%d): %s\n", ret, buf);
}
}
}
}
_out:
if (-1 != fd1)
close(fd1);
if (-1 != fd2)
close(fd2);
return ret;
}