C: 阻塞读应该返回,如果文件描述符被删除 [英] C: blocking read should return, if filedescriptor is deleted

查看:67
本文介绍了C: 阻塞读应该返回,如果文件描述符被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以被阻止的方式从设备/文件描述符读取.可能会发生,在不同的线程中关闭设备并删除文件描述符.不幸的是,读取没有返回或注意到并一直阻塞.

I am reading in a blocked way from a device/filedescriptor. It might happen, that in a different thread the device is closed and filedescriptor is deleted. Unfortunatly the read doesn't return or take notice and keeps blocking.

作为一种解决方法,我可以使用 select 作为超时来执行 while 循环.如果发生超时,我可以检查文件描述符,以防万一它不调用读取而是返回.

As a workaround I could do a while loop with select as a timeout. If a timeout happens, I can check the filedescriptor and in case it is gone not calling read but return.

我想知道在 Linux-C 中是否有更好的方法?

I am wondering, if there is a better way in Linux-C ?

推荐答案

您所描述的代码具有固有的竞争条件 - 如果另一个线程可能阻塞文件描述符上的 read()当你 close() 那个文件描述符时,另一个线程也可以调用 read() 代替.

The code you are describing has an inherent race condition - if another thread could be a in blocking read() on a file descriptor when you close() that file descriptor, the other thread could just as well be just about to call read() instead.

您不能调用 close() 除非您知道所有其他线程根本不再能够使用该文件描述符.

You can't call close() unless you know that all other threads are no longer in a position to be using that file descriptor at all.

处理您描述的情况的最简单方法是让一个线程成为每个文件描述符的拥有"线程,该线程负责关闭文件描述符.其他线程不会直接关闭它——而是在某些共享数据结构中将文件描述符标记为要关闭"并唤醒拥有它的线程.

The easiest way to handle cases like you describe is for one thread to be the 'owning' thread of each file descriptor, that is responsible for closing the file descriptor. Other threads don't directly close it - instead they mark the file descriptor as "to be closed" in some shared data structure and wake up the owning thread.

您可以通过在 read() 中不阻塞而是在 select()poll() 中阻塞来唤醒拥有线程 与另一个文件描述符 - 通常是管道 - 在集合中以及目标文件描述符.通过写入管道的另一端来唤醒线程.

You can make it possible to wake the owning thread by having it not block in read() but instead block in select() or poll() with another file descriptor - usually a pipe - in the set as well as the target file descriptor. The thread is woken by writing to the other end of that pipe.

这篇关于C: 阻塞读应该返回,如果文件描述符被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆