develooper Front page | perl.perl5.porters | Postings from October 2013

Closing "all open" filehandles in a Win32 pseudofork

From:
Paul "LeoNerd" Evans
Date:
October 6, 2013 14:51
Subject:
Closing "all open" filehandles in a Win32 pseudofork
Message ID:
20131006155106.5869316f@shy.leonerd.org.uk
I'm running up against an awkward edge-case in the MSWin32
threads-bases pseudoforks, on how to close open filehandles. Allow me a
moment to explain from the POSIX (e.g. Linux) case.

After I fork(), the child process builds a list of all the filehandles
it wants to keep hold of, to then close all the others:

  my @keep_handles = ...;
  my %keep_fds = map { $_->fileno => 1 } @keep_handles;

  $keep_fds{$_} or POSIX::close($_) for 0 .. FD_MAX;

I have to use POSIX::close() here because I don't have the filehandle
GLOB refs, I'm just iterating possible filenumbers. 

On MSWin32 though this is "too strong"; the POSIX::close() function
actually closes the filehandle properly in the containing (real OS)
process that implements all the pseudofork children; so now the parent
finds it has lost the filehandle as well.

However, I can't immediately use CORE::close($fh) because I don't have
filehandles - I want to close all of them that are open except for the
few I need kept open.

Having gone source-diving I find in win32/win32io.c:

  24 typedef struct
  25 {
  26  struct _PerlIO base;       /* The generic part */
  27  HANDLE         h;          /* OS level handle */
  28  IV             refcnt;     /* REFCNT for the "fd" this represents */
  29  int            fd;         /* UNIX like file descriptor - index into fdtable */
  30 } PerlIOWin32;
  31 
  32 PerlIOWin32 *fdtable[256];

This looks massively useful - either I want to iterate over (faked)
GLOB refs pointing into this table, or I want a way to directly
->refcnt-- the items in it. I am -guessing- at this point, that the way
fork() works on MSWin32 is that the refcnt of every handle gets
incremented, so that CORE::close() can keep track of when pseudoforks
close it, to be able to close them when required.

Are there any perl-level ways I can interact with this table more
directly? It seems an easy way to get the behaviour I want on Windows.

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk
ICQ# 4135350       |  Registered Linux# 179460
http://www.leonerd.org.uk/



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About