中断被阻止的 I/O 功能

interruption of blocked I/O functions

我有一个线程,它读取串行设备 (/dev/ttyUSB0),并将数据写入标准输出:

void io_thread_func () {

    int serial_port = open(settings.port, O_RDWR);

    while (1) {

        char buf[100];

        int n = read(serial_port, buf, 100);

        fwrite(buf, 1, n, stdout);

    }

}

如何从另一个线程中断“read(...)syscall? 我可以从另一个线程调用“close(serial_port)”来中断所有 I/O 阻塞函数吗? (我需要中断 I/O 阻塞函数才能正确关闭线程)

How i can interrupt "read(...)" syscall from another thread ? Can i call "close(serial_port)" from another thread to interrupt all I/O blocking functions ? (i need to interrupt I/O blocking functions to close the thread correctly)

您可以向线程发送信号。这将中断 read 函数。

绝对不能从另一个线程关闭串口。那会导致各种灾难。考虑:

  1. 此线程即将调用 read 但尚未调用。
  2. 另一个线程在 serial_port 上调用 close
  3. 在第一个线程可以调用 read 另一个线程 accepts 用于关键内部系统目的的传入套接字连接之前。
  4. 该线程恰好获得与 serial_port 相同的描述符。
  5. 此线程调用 read 然后 fwrite,将关键套接字上接收到的数据转储到 stdout

还好 stdout。因为一个错误曾经导致完全相同的情况——除了敏感数据是从 Internet 发送到随机入站连接而不是 stdout