laziness, impatience, and hubris | |
PerlMonks |
Re^2: Open a file on a specific file descriptor?by polettix (Vicar) |
on Jan 02, 2008 at 10:25 UTC ( [id://659945]=note: print w/replies, xml ) | Need Help?? |
Well, opening the fd you like isn't difficult at all, as dave_the_m suggested - even if I have to admit that things might be less portable than I'm impling here. Pragmatically, what I see in my Linux system is that the lowest available file descriptor is always going to be used.
The first thing you have to pay attention to is the starting file descriptor. For a brand new process, you should get 0, 1 and 2 assigned to standard input, standard output and standard error resp. (I know you *already* know this, but bear with me). So, if you really want to start from 4 instead of 3 (I wonder why, but I'm sure you have a good reason), you first have to do a fake open to get the spare file descriptor: Then, pipe calls come in pairs, so you can get the couples you want: To take into account your need for handles 0 and 1 as well:
The best thing to do is probably write a subroutine for this: I know, using this for each pair means that you will re-open fake handles for lower descriptors at each call. Feel free to optimise, if you think this is really needed :) Update: if you're wondering why I'm explicitly close-ing the handles instead of letting scoping do its work, I have to admit that I've been biten by this. In particular, I noted that the file descriptor 0 wasn't released when getting out of the while. If anyone can shed a light on it I'd be grateful! This was the original loop: and of course I had no close pop @fakes; line after it. I thought that it could be that any time you open file descriptor 0, you can access it via STDIN (that is *STDIN{IO}), so when $fh goes out of scope the handle's reference count does not drop to zero, and auto-closing is not triggered. Hey! Up to Dec 16, 2007 I was named frodo72, take note of the change! Flavio
In Section
Seekers of Perl Wisdom
|
|