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 (11:56)
From: Oliver Bandel <oliver@f...>
Subject: Re: [Caml-list] Closing all open file descriptors
Zitat von Dave Benjamin <>:

> 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;
> Is there a better way?

Yes: Do not start your daemon from a big program,
start it from scratch.
Normally only stdin, stdout and stderr are opened.
So, when your daemon starts as a separate program,
you only need to close these descriptors.

If you want to know, how many open files are allowed,
on Unix-systems you can use the MAX_OPEN value in C programs.

As a general rule you could remember: fork as early as possible.
If you have a huge memory usage and the usage of the different processes
is varied in a wide range, forking before allocating mem means to
save ressources.
If you first allocate huge memory portions and then fork,
you have wasted memory. It normally does not matter
until the moment you change your data, because modern Unix's and Linux
use COW (Copy On Write). But when you then change your data,
a lot of ressources will be needed.

So: fork early, allocate ressources afterwards.

There is no reason to do it diiferently in respect to usage of filedescriptors.

If you write a daemon, make it a separate program,
not making a fork from a huge application.

So, why should it be necessary then, to close file descriptors?
Why should they be opened, if you start a daemon as a stand-alone?

(Why should there be a need for a daemon to be forked off from
a big app, so that you could assume that many descriptors are open?)