gpt4 book ai didi

c - Ater 增加 sleep() fd 无法正常工作

转载 作者:行者123 更新时间:2023-11-30 17:33:30 25 4
gpt4 key购买 nike

我正在做Linux串口编程,并在延迟一段时间后定期从fd读取和写入消息。当延迟小于 5( sleep 5)) 秒时,我的端口正常工作非常无限的时间,但是当我增加延迟时间( sleep (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:");

}

这只是一个粗略的代码,用于显示我正在使用的配置..请帮助

最佳答案

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:

关于c - Ater 增加 sleep() fd 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23730206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com