繁体   English   中英

强制读取系统调用阻止

[英]Force read system call to block

我有一个程序可以读取和写入串行端口。 我有一个读取器线程,它读取数据并向共享内存提供信息。 读者线程应该睡眠,直到数据可用。 所以我想让read()系统调用来阻塞调用线程。 考虑手册页,除非您提供O_NONBLOCK open ,否则应始终禁止read 但我有一个活动的线程,其中read连续返回-1 同时改变VTIMEVMIN并没有什么不同。 这是端口的打开方式:

fd = open(portName.str().c_str()/*/dev/ttyS2*/, O_RDWR | O_NOCTTY);
    if (fd < 0) // if open is not successful
    {
        cerr << ERROR << "Unable to open `" << portName << "'." << endl;
        return false;
    }
    else
    {
        cout << INFO << "Port " << portName.str() << " successfully opened."
                << endl;
        cout << INFO << "Configuring port..." << endl;
        fcntl(fd, F_SETFL,0);
        struct termios port_settings; // structure to store the port settings in
        cfsetispeed(&port_settings, B38400); // set baud rate
        cfsetospeed(&port_settings, B38400); // set baud rate
        port_settings.c_cflag |= CLOCAL | CREAD;
        port_settings.c_cflag &= ~CRTSCTS; // disable H/W flow control
        port_settings.c_lflag &= ~( ISIG | // disable SIGxxxx signals
                IEXTEN | // disable extended functions
                ECHO | ECHOE); // disable all auto-echo functions
        port_settings.c_lflag &= ~ICANON ; // raw mode
        port_settings.c_oflag &= ~OPOST; // raw output
        port_settings.c_iflag &= ~(IXON | IXOFF | IXANY); // disable S/W flow control;
            // Following values do not change timout in runtime:
        port_settings.c_cc[VTIME] = 2; // wait 0.2 second to get data - 
        port_settings.c_cc[VMIN] = 0;

        port_settings.c_cflag = (port_settings.c_cflag &= ~CSIZE) | CS8; // set data byte size
        port_settings.c_cflag &= ~CSTOPB; // set stop bit 1
        port_settings.c_cflag &= ~PARENB; // set no parity
        port_settings.c_iflag |= IGNPAR; // ignore parity
        port_settings.c_iflag &= ~(INPCK | ISTRIP | PARMRK);

        // Set
        if (tcsetattr(fd, TCSANOW, &port_settings) < 0)
        {
            cerr << ERROR << "Unable to configure serial port." << endl;
            return false;
        }
        else
        {
            cout << INFO << "Port `" << portName.str()
                    << "' configuration was successful." << endl;
        }

在读者线程中:

byte buffer[256];
while (true)
{
    int packetSize = read(fd, buffer, 256);
    if (packetSize > 0)
    { 
      // use data - this code is never run 
    }
    else 
    {
       // print error - we're always here. no matter how long timout is
    }
 }

这里要考虑几件事。

首先,由于多种原因,读取可以返回。 任何类型的中断都会导致读取解除阻塞并返回-1,文件也可能存在问题。 检查errno变量以获取有关返回-1的更多信息。 可能的errno值的描述在阅读手册页中

其次,在您解决了上述问题之后,当数据可用时,不能保证读取只能在一次读取中为您提供整个网络数据包,因此您可能需要从多次读取中重新组合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM