james.oden has asked for the wisdom of the Perl Monks concerning the following question:

I have a daemon library that attempts to close all file descriptors after it forks. Unfortunately, when closing using POSIX::close() so you can close with just an fd, it is of course not cleaning up file handles associated with the fd. This causes highly interesting bugs...

What I need is a way to close all file handles associated with a fd, or get references to all the filehandles's associated with an fd so I can close them. Does anyone know how to do this.

BTW, I'm looking at the perlio.c code right now to figure out how I might do this in C, but if its already been done or there is a way that would be so helpful and appreciated.

Thanks...james

  • Comment on Closing all filehandles associate with an fd

Replies are listed 'Best First'.
Re: Closing all filehandles associate with an fd
by zwon (Abbot) on Dec 11, 2009 at 23:06 UTC

    There's no simple way to close all files. You can try:

    use POSIX; POSIX::close($_) for (0..1024);
    Also exec(3) will close most of the fds

    Update: also read how to close all files

    Also this should be POSIX::close

Re: Closing all filehandles associate with an fd
by ikegami (Patriarch) on Dec 12, 2009 at 00:03 UTC
    What do you mean by "not cleaning up the file handles associated with the fd"?
Re: Closing all filehandles associate with an fd
by zentara (Cardinal) on Dec 12, 2009 at 12:40 UTC
    .... you might be able to look at the fd file numbers in /proc/$pid/fd, store them in arrays as they get created.... i.e. as you open a filehandle, get it's fd and store it, so you can delete them later by fd...... i wonder what would happen if you just recursively delete /proc/$pid/fd/* .... i hesitate to try....maybe it would make zombies? with fd's 0,1,, and 2 gone?

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku

      You don't even need the PID, because /proc/self is a symlink to the /proc/$pid directory provided by the kernel, at least on Linux 2.x. The downside is that neither /proc/self nor /proc/$pid exist on all operating systems. And even on systems where a proc filesystem exists, it is not always mounted. Deleting /proc/$pid/fd/$n will probably just fail with a "permission denied" error, simply because it makes no sense.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)