如何在vxworks或linux上取消阻止的read / recvfrom系统调用

任务I中

... while (1) { if (running == false) break; ret = read(fd, buf, size); /* Or: ret = recvfrom(sock, buf, size, 0, NULL, NULL); */ ... } 

任务II中

 ... running = true; /* ioctl(fd, FIOCANCEL, 0); */ close(fd); /* Or: close(sock);*/ 

任务II中应该做什么来取消被阻止的任务我

vxworks中 ,有一个函数ioctl(fd, FIOCANCEL, 0)来取消阻塞的读取或写入,但它无法工作。 可能是因为司机不能支持“FIOCANCEL”

如何在vxworks和linux中编写任务II? 或者还有其他办法来完成我的任务吗?

在linux上取消read / recvfrom调用是不可能的 。 您无法使用相同的API编写这些任务。 在Linux上,您可以使用epoll和O_NONBLOCK来创建取消read / recvfrom的语义。

对于linux和vxworks,使用相同的代码是不可能的

不要使用阻塞IO,这是创建没有(可达)退出条件的线程的经典案例,我认为这是一个错误。 如何运行线程的最简单示例如下:

 volatile bool _threadRunning = true; void taskI() { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); while (_threadRunning == true) { ret = read(fd, buf, size); if (ret > 0) { // process buffer } else { // sleep for 1 millisecond or so... } } close(fd); } void taskII() { _threadRunning = false; _taskI.join(); }