当前位置: 技术问答>linux和unix
Linux中串口read怎样阻塞的方式读入数据
来源: 互联网 发布时间:2016-08-24
本文导语: pthread_mutex_lock(&ptty->mt); ret = read(ptty->fd, pbuf, 1); //由于read并不阻塞 要监听随时可能来数据的串口 得不停的循环的查看 效率好低 if(ret fd, pbuf, ......);//使得这儿没有串...
pthread_mutex_lock(&ptty->mt);
ret = read(ptty->fd, pbuf, 1); //由于read并不阻塞 要监听随时可能来数据的串口 得不停的循环的查看 效率好低
if(ret fd, pbuf, ......);//使得这儿没有串口数据时阻塞,有串口数据了就读到
//避免不停的循环+sleep() 耗费ARM板资源,而且有时还漏读
//有的说用什么fcntl,ioctl 这两不太懂,希望可以解释清楚点
*/
pthread_mutex_unlock(&ptty->mt);
附加:那位大牛要是能告诉个大概的 Linux C 中哪些IO操作函数时阻塞 哪些不是
或能使用什么方法实现阻塞或不阻塞
|
Reading data from a port is a little trickier. When you operate the port in raw data mode, each read(2) system call will return however many characters are actually available in the serial input buffers. If no characters are available, the call will block (wait) until characters come in, an interval timer expires, or an error occurs. The read function can be made to return immediately by doing the following:
fcntl(fd, F_SETFL, FNDELAY);
The FNDELAY option causes the read function to return 0 if no characters are available on the port. To restore normal (blocking) behavior, call fcntl() without the FNDELAY option:
fcntl(fd, F_SETFL, 0);
This is also used after opening a serial port with the O_NDELAY option.
fcntl(fd, F_SETFL, FNDELAY);
The FNDELAY option causes the read function to return 0 if no characters are available on the port. To restore normal (blocking) behavior, call fcntl() without the FNDELAY option:
fcntl(fd, F_SETFL, 0);
This is also used after opening a serial port with the O_NDELAY option.
|
两个都为非零时任意一个条件达到都返回
如果两个条件都为零,则马上返回
如果一个为非零,则仅仅关注该非零条件
如果两个条件都为零,则马上返回
如果一个为非零,则仅仅关注该非零条件
|
还有比manpages更好的手册么。。。
|
open(dev, O_NONBLOCK|O_RDWR)..... 非阻塞
|
fd = open( Dev, O_RDWR | O_NOCTTY);
options.c_cc[VTIME] = 0; /* 等待100ms* 该值等待时间就返回 */
options.c_cc[VMIN] = 1; /* 接收到该值数量字节就返回 */
/* 上面两个条件为非零时才有效,两个都为非零时任意一个条件达到都返回,如果两个条件都为零,则马上返回 */
tcflush(fd,TCIFLUSH); /* Update the options and do it NOW */
if (tcsetattr(fd,TCSANOW,&options) != 0){
return ERRCOM_SETATTR;
}
return ERRCOM_OK;
|
貌似阻塞与非阻塞读写有专门的函数,不记得了。