如何唤醒termios UART阻止读取?

时间:2020-05-24 16:20:28

标签: c linux multithreading serial-port signals

我正在线程中使用阻塞read

当程序必须结束时,我发送了一个sigint,它设置了一个标志来结束线程。但是由于我正在等待阻塞读取,因此线程永远不会停止。有办法唤醒阅读吗?

mFd = open(mPort.c_str(), O_RDWR | O_NOCTTY | O_SYNC);
if(mFd == -1){
    m_logger.error("Unable to open UART. Ensure it is not in use by another application");
}

struct termios settings;

tcgetattr(mFd, &settings);
cfsetispeed(&settings, mBaudrate);

settings.c_cflag &= ~PARENB; /* no parity */
settings.c_cflag &= ~CSTOPB; /* 1 stop bit */
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */
/* echo off, echo newline off, canonical mode off,
 * extended input processing off, signal chars off
 */
settings.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
settings.c_oflag = 0; /* Turn off output processing */
settings.c_cflag &=  ~CRTSCTS;
/* Read settings :
 * To understand the settings have a look at man 3 termios
 * ``Canonical and noncanonical mode`` section
 */
settings.c_cc[VMIN]   =  20; /* read doesn't block , one byte is enough to satisfy the read */
settings.c_cc[VTIME]  =  TIMEOUT_READ_BYTE_DS; /* Interbyte timer. Timeout in ds */
settings.c_cflag     |=  CREAD;

/* Flush Port, then applies attributes */
tcflush(mFd, TCIFLUSH);
if (tcsetattr(mFd, TCSANOW, &settings) < 0){
    m_logger.error("Error during the set of the attributes to the file descriptor");
    mFd= -1;
} /* apply the settings */
}

您的阅读过程类似于

while (EndThread==false){
    memset(buffer, 0, BUFFER_SIZE);
    bytesRead = read(mFd,buffer,BUFFER_SIZE);     //<----- I block here until I read something
    if(bytesRead < 0){
        m_logger.error("Error occurred during the reading of the serial port");
    } 
    else
    {....}

我不知道是否有可以唤醒read的信号,或者我是否可以自己写在缓冲区上以唤醒它。我找不到有关它的任何信息。有人可以帮我吗?

0 个答案:

没有答案