fork/exec & close file descriptors

Chris Angelico rosuav at gmail.com
Wed Jun 3 09:32:23 EDT 2015


On Wed, Jun 3, 2015 at 11:21 PM,  <random832 at fastmail.us> wrote:
> On Wed, Jun 3, 2015, at 09:08, Marko Rauhamaa wrote:
>> random832 at fastmail.us:
>>
>> > Why does the child process need to report the error at all? The parent
>> > process will find out naturally when *it* tries to close the same file
>> > descriptor.
>>
>> That's not how it goes.
>>
>> File descriptors are reference counted in the Linux kernel. Closes are
>> no-ops except for the last one that brings the reference count to zero.
>>
>> If the parent should close the file before the child, no error is
>> returned to the parent.
>
> Why would the parent close it before the child? Your scenario doesn't
> seem to have anything to do with how people actually use subprocesses.

Write an editor that opens a file and holds it open until the user's
done with it. Have something that lets you shell out for whatever
reason. Then trigger the shell-out, and instantly SIGSTOP the child
process, before it does its work - or just have a really heavily
loaded system, so it can't get a time slice. Now close the file in the
UI, which results in the file being closed in the parent. Right, now
let the child run... and there it goes, closing the file.

Mightn't be a common situation (given that the amount of code executed
between forking and closing FDs is not going to be much, and isn't
going to involve reading from disk or anything), but it can certainly
happen.

ChrisA



More information about the Python-list mailing list