Send output from exec to file perl

Viewed 710

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.

2 Answers

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";
 }

I suppose if you just need to print to file, this should work.

easiest possible way to capture the output is by using backticks.

use strict;
use warnings;

open (my $file, '>', 'output.log');
my $pid = fork;
if (!defined $pid) {
    die "Cannot fork: $!";
}
elsif ($pid == 0) {
    print $file `/usr/bin/echo done`;
}
Related