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: Dave Benjamin <dave@r...>
Subject: Re: [Caml-list] Closing all open file descriptors
Erik de Castro Lopo wrote:
> Dave Benjamin wrote:
> 
>> I'm writing a daemon and I would like to be able to close all open file 
>> descriptors. As far as I can tell, there is no way to determine the 
>> maximum number of file descriptors available, and neither is there a way 
>> to get a file descriptor from an integer. The best I've come up with is 
>> the following:
>>
>>    for fd = 0 to 1024 do
>>      try Unix.close (Obj.magic fd : Unix.file_descr)
>>      with Unix.Unix_error _ -> ()
>>    done;
> 
> I remember doing this in a daemon I wrote years ago in C but didn't
> do it for a daemon I wrote recently in Ocaml (much nicer for daemons
> than *any* other language).

Did your program "daemonize" at all, then? Or did you use daemontools?

> My curiosity was piqued, so I did a bit of a search and found the
> rational for this here:
> 
>     http://cloud9.hedgee.com/scribbles/daemon
> 
> in particular the fghack tool which prevents a daemon that doesn't
> close all file descriptors from going into the background :
> 
>     http://cr.yp.to/daemontools/fghack.html

I never really thought all that much about closing file descriptors 
until recently, when I discovered that Apache leaks a bunch of 
descriptors to its modules, one of which is the listening socket which 
can prevent Apache from restarting. So, I've been reading Advanced 
Programming in the UNIX Environment to try to fill in the many gaps in 
my understanding of what's going on here.

I can see how it might be annoying to try to make a daemon run on stdio 
instead, and not being able to keep the file handles open... but it 
seems like daemons could be written to work either way if designed with 
some care.

> One possible solution to this would be a function written in C and
> wrapped in Ocaml that does the same as the Obj.magic hack above.

Yeah, the whole operation could be done in a C function too, and 
probably wouldn't be much more code to write.

Thanks for the interesting links,
Dave