select


#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;
}

 

转载于:https://my.oschina.net/u/244869/blog/41820

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值