file redirection

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have a perl program that opens a log file and than prints to it,
that part works well


if (! open (LOG, ">>$logfile"))
    print STDERR "Cannot open logfile $logfile $!\n";
    exit 1;

print LOG "Hello world\n";

I want to do something like this and it is not working. Note I want
to redirect the output of the kill command to the same logfile, is
possible? If so, what am I missing. Note: at this point LOG is still

system("kill -USR1 \"$1\" > LOG 2>\&1");


Re: file redirection writes:

Quoted text here. Click to load it

LOG is not available as a filehandle name in any exec'd programs, and
you have to use numeric arguments in the shell (which you can get from
fileno) to denote file descriptors.

The only file descriptors that are passed on to child processes by
default are STDOUT, STDIN and STDERR. This is handled using the
FD_CLOEXEC (close-on-exec) flag. See the POSIX standard, or a decent
book on UNIX programming.

So, you basically have 2 options: remove the close-on-exec flag on LOG
(see the code below), or redirect STDERR to some log file and then
exec. The latter is simpler and usually what you want anyway for perl
code, since it means your die()/warn() messages go to that log.

use strict;
use warnings;

open LOG,">log.log" or die $!;

# remove the close-on-exec flag from LOG
fcntl(LOG, F_SETFD, fcntl(LOG, F_GETFD, 0) & (-1 ^ FD_CLOEXEC));

my $fn = fileno(LOG);
system qq(echo "test" >&$fn 2>&$fn) and die;

Joost Diepenmaat | blog: | work: /

Re: file redirection wrote:

Quoted text here. Click to load it

system doesn't know what the LOG filehandler is there.

Since you're doing it this way, perhaps just only use:

system("kill -USR1 \"$1\" > $logfile 2>\&1");

Instead of using open() and then system()?

Also, you probably want >> instead of > to append to the file, rather
than overwrite it by the sound of it.
Tim Greer, CEO/Founder/CTO,, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting.  24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!

Re: file redirection wrote:
Quoted text here. Click to load it

perldoc -f kill

Quoted text here. Click to load it

Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

Site Timeline