File Descriptors

Hi,
I have written a daemon process, to perform certain operations in the background.
For this I have to close, the open file descriptors,

Does anybody know how to find out the number of open file descriptors ?

Thanks in Advance,
Sheetal

I don't know any portable way for a process to find out the number of files it has open.

But consider this case...I open 16 files and allocate fd 0 through fd 15. Then I close fd 0 through fd 14. This leaves only fd 15 open. If you could magically find out that only one file is open, how would that help you? You still don't know which fd to close.

The shell will allocate fd 0, 1, and 2 and pass these to you. Your program should keep track of which files it opens.

If you have lost track of want files are open, the only thing I can suggest to do a getrlimit() to obtain the highest possible fd that could ever be allocated. Then close all possible fd's. The close call will fail if the file is not open, so you just ignore that error.

In general when you write a daemon process you...

Become a session leader - fork()
Become a process-group leader - setsid()
Dissociate from controlling terminal - setsid() normally does this too.
chdir to '/' - chdir()
Set file creation mask to 0 - umask(0)

You still need to close unneeded descriptors. Assuming you
haven't opened anything, you can simply do...

for (i = 0; i < 10; i++)
close(i);

As Perderabo says, "The close call will fail if the file is not open,
so you just ignore that error."

At this point, you have initalized your daemon process.
A great reference book with examples of this is...
Advanced Programming in the UNIX Environment
by W. Richard Stevens