read串口数据实现阻塞方式的两种方法
方法一
以阻塞方式打开串口设备,即在open中去掉非阻塞参数O_NDELAY(O_NOBLOCK),并且设置c_cc[VMIN]>0,c_cc[VTIME] = 0。
/*----------------Open the ttyUSB0 SerialPort node-------------------*/
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
/* O_RDWR - Read/Write access to serial port */
/* O_NOCTTY - No terminal will control the process */
/* O_NDELAY - Open in noblocking mode,read will not wait */
if(fd == -1) /* Error Checking */
{
printf("\n Error! in opening ttyUSB0");
return -1;
}
else
{
printf("\n Success! in opening ttyUSB0");
}
/* These parameters are important,just when fd is in blocking mode they will be used */
ttyUSB0paras.c_cc[VMIN] = 1; /* Read at least xxxx characters */
ttyUSB0paras.c_cc[VTIME] = 0; /* Wait indefinetly */
方法二
以非阻塞方式打开串口设备,然后使用fcntl函数设置为阻塞方式。
/*------------------------------- Opening ttyUSB0 in blocking mode-------------------------------*/
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
/* O_RDWR - Read/Write access to serial port */
/* O_NOCTTY - No terminal will control the process */
/* O_NDELAY - Open in noblocking mode,read will not wait */
if(fd == -1) /* Error Checking */
{
printf("\n Error! in opening ttyUSB0");
return -1;
}
else
{
printf("\n Success! in opening ttyUSB0");
}
/*----------------------------set in blocking mode--------------------------------------------------*/
if(fcntl(fd, F_SETFL, 0)<0)
printf("fcntl failed!\n");
else
printf("fcntl=%d\n",fcntl(fd, F_SETFL,0));