强制读取系统调用以阻止
Force read system call to block
我有一个读取和写入串行端口的程序。我有一个读取器线程,用于读取数据并向共享内存提供信息。读取器线程应休眠,直到数据可用。所以我想进行read()
系统调用以阻止调用线程。考虑到手册页,除非您向open
提供O_NONBLOCK
,否则read
应始终阻止。但是我有一个活动线程,其中read
连续返回-1
。所以改变VTIME
和VMIN
并没有区别。 这是端口的打开方式:
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 值的说明在读取手册页中
其次,在解决了上述问题之后,当数据可用时,不能保证在一次读取中为您提供整个网络数据包,因此您可能需要从多次读取中重新组合。
相关文章:
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- 如何将C++系统调用连接到 freertos
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 在嵌入式系统中读取文件的内存碎片
- 系统调用:一次和多次,哪个更好?
- 使用路径和空格的系统调用
- 是否有等效于 macOS 上的 clone() 系统调用?
- 从C++调用系统调用节点?
- C++测试程序中的非法系统调用(对角矩阵元素程序的总和)
- 英特尔 Pin:如何获取系统调用的返回地址
- 如何使用低级系统调用从 stdin 和输入文件中获取字节数
- 使用模拟器C++从RISC-V裸机程序调用printf系统调用时失败
- 动态执行的 ARM ASM 系统调用,可从C++重新定位
- 如何知道我正在使用的Linux OS是否具有特定的系统调用
- 强制读取系统调用以阻止
- 使用读取系统调用C++输出文本
- Linux 读取系统调用不从文件读取
- 如何在C++中读取系统调用失败时显示的故障日志消息
- 让系统调用' select() '阻塞,直到套接字获得要读取的内容