Results 1 to 6 of 6
Hi,
I have read() blocked on a file in one thread and I need to close() the file from another thread. What is the safest way to do it?
TIA...
- 06-19-2009 #1Just Joined!
- Join Date
- May 2009
- Posts
- 6
Closing a file blocked on Read
Hi,
I have read() blocked on a file in one thread and I need to close() the file from another thread. What is the safest way to do it?
TIA
- 06-19-2009 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
You need to interrupt the reading thread so it can stop the operation. Or, you should be able to close the file, and the reading thread should return from the operation with an error. I don't know for sure if that will work since I haven't personally tried it.
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 06-20-2009 #3Just Joined!
- Join Date
- May 2009
- Posts
- 6
I tried the option of closing the file descriptor but the other thread blocked on read does not return from read(). Any other suggestions anyone?
- 06-20-2009 #4Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
You need to interrupt the reader thread. Usually it is a good idea to set a timer to interrupt a read for just such cases. I'm not sure that interrupting the reader thread itself will pull it out of the kernel operation that read(0 entails. You might want to rethink your design to avoid such "race" conditions.
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 06-21-2009 #5Just Joined!
- Join Date
- Jun 2009
- Location
- Toronto
- Posts
- 18
You could open your file with a non-blocking file handle and then use select() to read from it. This way your reader would know when the file was closed, because there would be an error on the read.
- 06-21-2009 #6
You can use the system call tkill() to send a signal to a specific thread. You will obviously need to create a handler for whatever signal you send, but remember that handlers are per-process, whereas this signal will be per-thread.
I disagree with Rubberman's claim that you should set a timer to catch this, however. Timers work on a predetermined time limit, which may or may not correspond to the particular case. Having the thread interrupted by another thread once it must be interrupted ensures that it will not be interrupted too early.
Before doing any of this, by the way, I would recommend figuring out why your thread is blocking, and addressing that instead. It may be possible to handle this condition in the reader thread, and simplify matters drastically.DISTRO=Arch
Registered Linux User #388732


Reply With Quote