Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

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: 2007-09-14 (01:03)
From: Erik de Castro Lopo <mle+ocaml@m...>
Subject: Re: [Caml-list] Closing all open file descriptors
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).

My curiosity was piqued, so I did a bit of a search and found the
rational for this here:

in particular the fghack tool which prevents a daemon that doesn't
close all file descriptors from going into the background :

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.

Erik de Castro Lopo
"I have long argued that the entertainment industry doesn't want
people to have computers. Computers give users too much capability,
too much flexibility, too much freedom. The entertainment industry
wants users to sit back and consume things. They are trying to
turn a computer into an Internet Entertainment Platform, along the
lines of a television or VCR. This bill is a large step in that
direction."  -- Bruce Schneier