Version française
Home     About     Download     Resources     Contact us    
Browse thread
Closing all open file descriptors
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Ville-Pertti Keinonen <will@e...>
Subject: Re: [Caml-list] Closing all open file descriptors

On Sep 14, 2007, at 1:56 AM, Dave Benjamin wrote:

>   for fd = 0 to 1024 do
>     try Unix.close (Obj.magic fd : Unix.file_descr)
>     with Unix.Unix_error _ -> ()
>   done;
>
> Is there a better way?

While I don't have a solution for your general problem (other than  
having your program launched by a known mechanism), I recommend that  
you never close the file descriptors for stdin, stdout and stderr.   
Subsequent opens will end up reusing those file descriptor numbers,  
but system libraries will still consider them valid (via libc).  This  
can cause some very strange bugs.

The safe way to detach stdio is to open /dev/null for writing, dup2  
that over stdout and stderr, open /dev/null for reading and dup2 that  
over stdin (obviously you can close the newly opened descriptors),  
thus you never run anything without valid stdio file descriptors.