fxia has asked for the wisdom of the Perl Monks concerning the following question:

Here is the problem:

Parent redirects STDOUT and STDERR to something else and then fork.

The child process needs to exec an external problem, e.g., "tar -cf - something". But the external problem relies on the fact that stdout and stderr are with file descriptor 1 and 2.

Since stdin is not redirected yet, I can get the tty name and reopen STDOUT and STDERR in the child process to the tty before exec(). However this seems not working, because the new STDOUT and STDERR will have fds different from 1 and 2.

In essence, I need to have dup2(oldfd, newfd) functionality in Perl. I wonder if there is anyway to do this? I looked at the Perl source code and it seems not possible.

Fred Xia

Replies are listed 'Best First'.
Re: dup2 exact file descriptor
by Fletch (Bishop) on Dec 03, 2001 at 23:50 UTC

    perldoc perlopentut has examples of reopening STD(OUT|ERR). You could also look at POSIX for its dup2().

Re: dup2 exact file descriptor
by andye (Curate) on Dec 03, 2001 at 23:39 UTC
    open(MHCONTEXT, "<&4"); is the example given in the open() section of the Camel Book - apparently it uses the dup2 syscall.

    andy.

Re: dup2 exact file descriptor
by IlyaM (Parson) on Dec 04, 2001 at 02:27 UTC