123 123 -3 years ago 189
Perl Question

Send output from exec to file perl

Problem



When running exec in perl, I am am unable to redirect the output to a file.

I am running vlc in the exec but since i doubt everyone has it set up I have replaced with echo below, it shows same behaviour for the example.

I am only interested in exec 'command','args' format of exec not the one that spawns a shell since it spawns a subshell with vlc which still prints to screen + other problems with killing it cleanly.




Code



use strict;
use warnings;

my $pid = fork;
if (!defined $pid) {
die "Cannot fork: $!";
}
elsif ($pid == 0) {
exec "/usr/bin/echo","done";
}





Tried



exec "/usr/bin/echo","done",">/dev/null";


As expected just prints ">/dev/null", but was worth a try.

exec "/usr/bin/echo done >/dev/null";


Runs sh which then runs echo, works here, but not in my actual problem with vlc, thought i would include anyway since someone will surely suggest it.

Question



How do I redirect output from this exec when using 'command','args' to a file?

Extra



Any more info needed please ask.

Answer Source

Turns out you can just change the file descriptors before the exec

use strict;
use warnings;

my $pid = fork;
if (!defined $pid) {
    die "Cannot fork: $!";
}
elsif ($pid == 0) {
    open STDOUT, ">", '/logger/log' or die $!;
    open STDERR, ">", '/logger/log' or die $!;
    exec "/usr/bin/echo","done";
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download