我从Linux Serial HOWTO页面借用了以下许多代码,以创建我的程序以从串口不断读取字符。我正在使用USB到串行端口适配器(由微创公司制造),因此我可以获得串行端口。 Linux将设备识别为/ dev / ttyUSB0。
当我在其他本机linux程序(例如输出转储程序)中使用该设备时,适配器可以正常工作,并且数据连续输入。但是,在我的程序中,数据输入大约10秒钟,然后我收到了没有更多数据,但是我知道适配器所连接的硬件还有更多数据需要处理。
此代码中是否可以解决某些问题,使我可以接收到无限个字符,而无需重新启动程序以接收更多字符?
我仍然希望使主线代码与串行例程异步,因为稍后我将添加更多代码。
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#define BAUDRATE B57600
#define MODEMDEVICE "/dev/ttyUSB0" /* My USB to serial converter */
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
void signal_handler_IO (); /* definition of signal handler */
int wait_flag=TRUE; /* TRUE while no signal received */
int main(){
int fd,res;
struct termios oldtio,newtio;
struct sigaction saio; /* definition of signal action */
char buf[255];
/* open the device */
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY);
if (fd <0) {perror(MODEMDEVICE); return -1; }
/* install the signal handler before making the device asynchronous */
saio.sa_handler = signal_handler_IO;
saio.sa_flags=0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
/* allow the process to receive SIGIO */
fcntl(fd, F_SETOWN, getpid());
/* Make the file descriptor asynchronous */
fcntl(fd, F_SETFL, FASYNC);
tcgetattr(fd,&oldtio); /* save current port settings */
/* set new port settings for canonical input processing */
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
/* loop while waiting for input. */
while (1) {
usleep(100000);
/* after receiving SIGIO, wait_flag = FALSE,
input is available and can be read */
if (wait_flag==FALSE) {
res=0;
/* Read up to 11 bytes which is remote packet length if file handle is valid */
if (fd){
res = read(fd,buf,11);
}
/* If there's at least 2 bytes (character plus ending null) then process it */
if (res > 1){
int n;
/* Print each character as 2-digit hex even if value is 0. */
for (n=0;n<(res-1);n++){
printf("%2X ",(unsigned char)buf[n]);
}
/* Print total number of characters received */
printf(" = %d\n",res);
}
wait_flag = TRUE; /* wait for new input */
}
/* Return to start of endless loop */
}
return 0;
}
/***************************************************************************
* signal handler. sets wait_flag to FALSE, to indicate above loop that *
* characters have been received. *
***************************************************************************/
void signal_handler_IO ()
{
wait_flag = FALSE;
}
答案 0 :(得分:2)
经典比赛条件:
wait_flag = TRUE;
在您的代码集printf()
之前被称为之前,例如在这些wait_flag
通话期间。
这时您的程序将停止。
一种补救措施可能是在if
之后立即设置poll()
-但我建议您考虑对Linux {{1}}进行异步I / O调用。