How can I redirect the output of a Perl () system to a file descriptor?

With the open command in Perl, you can use a file descriptor. However, I am unable to return the exit code using the open command in Perl.

With the system command in Perl, I can return the exit code of the program that I am running. However, I want to just redirect STDOUT to some file descriptor (without stderr).

My stdout will be the linear output of the key-value pairs that I want to insert into mao in perl. That is why I want to redirect only my stdout from my Java program to perl. Is it possible?

Note. If I get errors, errors are printed in stderr. One possibility is to check if anything is printed in stderr so that I can have a full Perl script.

+3
source share
4 answers

You can check IPC :: System :: Simple - it gives you many options for executing external commands, capturing their output and return values, and possibly dies if a bad result is returned.

+3
source

Canonically, if you are trying to get the text output of a forked process, I understand that backlinks are needed for this. If you need an exit status, you can check it with the special $?after variable , for example:

open my $fh, '>', "output.txt" or die $!;
print {$fh} `echo "Hello!"`;
print "Return code: $?\n";

Exiting STDERR from a command in backticks will not be captured, but instead will be written directly to STDERR in the Perl program from which it called.

+2

open -|. close , $?.

open my $fh, '-|', "$command";  # older version:  open my $fh, "$command |";
my @command_output = <$fh>;
close $fh;
my $command_status = $?;

perldoc -f close

, "close" false, , . ( , , $! 0.) , , $? "${^CHILD_ERROR_NATIVE}".

+1

.

open my $fh, '>', $file;
defined(my $pid = fork) or die "fork: $!";
if (!$pid) {
    open STDOUT, '>&', $fh;
    exec($command, @args);
}
waitpid $pid, 0;
print $? == 0 ? "ok\n" : "nok\n";
0

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


All Articles