Send output from exec to perl file

Problem

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

I run vlc in exec, but since I doubt everyone configured it, I replaced echo below, it shows the same behavior for example.

I'm only interested in the exec 'command', 'args' command for exec, and not the one that spawns the shell, since it spawns a subshell with vlc that still prints on the screen + other problems, 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"; } 

I tried

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

As expected, it just prints "> / dev / null", but it's worth a try.

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

Starts sh, which then starts the echo, works here, but not in my real problem with vlc, I thought that I would turn it on anyway, since someone would definitely suggest it.

Question

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

Extra

For more information, please ask.

+5
source share
2 answers

Turns out you can just change the file descriptors before 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"; } 
+3
source

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

The easiest way to capture output is to use reverse steps.

 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`; } 
0
source

Source: https://habr.com/ru/post/1272150/


All Articles