我正在进行linux串口编程,经过一段时间后定期读取和写入fd的消息。当延迟小于5(睡眠5)秒时,我的端口正常工作非常无限时间但是当我增加延迟时间(睡眠(20)或超过10秒)时,我的fd在2-3个消息周期后停止工作。你能告诉我为什么会有这种行为吗?我曾尝试过许多其他方面的延迟,但仍然是一样的。 下面是我的代码片段
struct termios port_settings;
int fd;
unsigned char msgR[10];
fd = open(PORT,O_RDWR|O_NOCTTY|O_SYNC);
if(fd == -1)
{
printf("Failed to open PORT: %s \n\n",PORT);
perror("Error:");
printf("\n\nunable to open port...\n\n========================\n\n");
}
bzero(&port_settings, sizeof(port_settings));
cfsetispeed(&port_settings, BAUDRATE);
cfsetospeed(&port_settings, BAUDRATE);
port_settings.c_cflag = (port_settings.c_cflag & ~CSIZE) | CS8;
port_settings.c_iflag &= ~IGNBRK;
port_settings.c_lflag = 0;
port_settings.c_oflag = 0;
port_settings.c_cc[VMIN] =10;
port_settings.c_cc[VTIME] = 5;
port_settings.c_iflag &= ~(IXON | IXOFF | IXANY);
port_settings.c_cflag |= (CLOCAL | CREAD);
port_settings.c_cflag &= ~(PARENB | PARODD);
port_settings.c_cflag |= 0;
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CRTSCTS;
tcsetattr (fd, TCSANOW, &port_settings);
while(1)
{
sleep(20); //time for betting for 1st client
write (fd,STATUS,5);
int n = read (fd, &msgR, sizeof(msgR));
if(n ==10)
{
printf("\nNumber of Bytes Read is-%d||MSG Recived : %s\n",n,msgR);
process(fd,msgR);
}
else
perror("Error while READ:");
}
这只是一个粗略的代码,用于显示我正在使用的配置..请帮助
答案 0 :(得分:0)
Aside from the numerous coding/port configuration errors,
as mentioned in the comments.
I suspect the root of the problem is
improper handling of the external device.
Perhaps the external device goes to sleep/hangs if not queried often enough.
The external device may/perhaps only respond to a status request
when 'it' is ready
if so, then there should be no need to invoke sleep()
as the select() will handle the
timing of the response from the external device.
A technique that will handle incoming data bytes,
as they become available,
is to use 'select()' to alert the program when data is available.
then use a 'read()' of only one char at a time,
with the read in a loop,
Note: this usually means three loops:
the pseudo code would be: (note: this is not well structured code)
configure the I/O port
loop1:
invoke sleep(x) // as mentioned above, this might not be necessary
invoke write( STATUS ) on the output stream
set byteCount = 0
loop2:
invoke select() on the input stream
loop3:
invoke a non-blocking read( a byte )
if read successful,
incr byteCount
save byte into an array of bytes
if enough bytes read, (in this case, 10 bytes)
perform any processing on the bytes read
goto loop1:
endif
else
handle any error
goto loop3:
endif
end loop3:
end loop2:
end loop1: