gpt4 book ai didi

c++ - 强制读取系统调用阻塞

转载 作者:行者123 更新时间:2023-11-28 03:26:12 25 4
gpt4 key购买 nike

我有一个从串行端口读取和写入的程序。我有一个读取数据并向共享内存提供信息的读取器线程。读取器线程应该休眠直到数据可用。所以我想进行 read() 系统调用来阻止调用线程。考虑到手册页,除非您向open 提供O_NONBLOCK,否则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
}
}

最佳答案

这里有几点需要考虑。

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

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

关于c++ - 强制读取系统调用阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13889609/

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