![](/img/trans.png)
[英]Difference when returning an array of chars or a pointer to char literal
[英]select() call not returning when chars on port
我有一個選擇呼叫,它似乎無法檢測到串行端口上的字符。 我有什么想念的嗎?
如果刪除上面塊中的read()代碼,則select將返回一會兒,直到清空現有的端口緩沖區,然后再檢測不到。
我正在向端口傳輸字符,運行minicom會在端口上顯示連續的輸入流。
有人可以看到這段代碼有什么問題嗎?
int main(void)
{
int ret;
char buf[1280];
fd_set m_Inputs; // fd_set for the select call for com input
int m_maxFD; // max FD for select() call.
struct timeval tv;
int fd1;
fd1 = open("/dev/ttyXR6", O_RDWR | O_NOCTTY | O_NONBLOCK);
fcntl(fd1, F_SETFL, 0);
struct termios options;
tcgetattr(fd1, &options); // Get the current options for the port...
// Set the baud rates...
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
// Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD | CS8);
options.c_cflag &= ~PARENB; // ignore parity
options.c_cflag &= ~CSTOPB; // 1 stop bit (2 if set)
options.c_cflag &= ~CSIZE; // clear the size bits
options.c_cflag &= ~CRTSCTS; //No hard flow control
options.c_cflag &= ~HUPCL; //Hang Up on last Close
options.c_cflag |= CS8; // reset the size to 8 bits / char
options.c_cc[VMIN]=1;
options.c_cc[VTIME] = 1;
options.c_oflag = 0;
options.c_lflag = 0; //ICANON;
// Set the new options for the port...
tcsetattr(fd1, TCSANOW, &options);
// test to make sure the characters are coming in on the port
for (short i =0; i < 60; i++)
{
ret = read(fd1, buf, 32);
buf[ret] = '\0';
cout << buf;
usleep(500);
}
fd_set rfds; // fd_set for the select call for com input
FD_ZERO(&rfds);
FD_SET(fd1, &rfds);
cout << endl << "FD1 = " << fd1 << endl;
while (1)
{
tv.tv_sec = 0;
tv.tv_usec = 1000;
ret = select(fd1 + 1, &rfds, NULL, NULL, &tv);
if (ret > 0)
{
ret = read(fd1, buf, 127);
buf[ret] = '\0';
cout << buf;
}
usleep(500);
}
return 0;
}
在返回之前,select()修改rfds以指示哪些描述符具有准備讀取的數據。
對於您而言,它是在1ms超時后第一次返回並且描述符上沒有可用數據時,它將從rfds集中刪除您的描述符,以指示沒有可用數據。 然后,當您下次在循環中再次調用select()時,rfds是一個空集,因此在此之后,它甚至都不再需要檢查描述符了。
每次循環時,都需要先調用FD_SET(fd1,&rfds)才能進行選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.