fork/exec & close file descriptors

Marko Rauhamaa marko at pacujo.net
Tue Jun 2 12:24:58 EDT 2015


Skip Montanaro <skip.montanaro at gmail.com>:

> On Tue, Jun 2, 2015 at 10:28 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
>>
>> The only problem is that you don't know how high you need to go in
>> general.
>
> Sure, but I didn't know anyway, so no matter what upper bound I choose
> (or what function I choose/implement), it's just going to be a guess.
> os.closerange just codifies the straightforward procedure.

Under linux, the cleanest way seems to be going through the files under
/proc/self/fd:

    def close_fds(leave_open=[0, 1, 2]):
        fds = os.listdir(b'/proc/self/fd')
        for fdn in fds:
            fd = int(fdn)
            if fd not in leave_open:
                os.close(fd)

No need for a upper bound.


Marko



More information about the Python-list mailing list