Getting STDOUT, STDERR, and response code from external *nix command in perl

后端 未结 4 1525
别跟我提以往
别跟我提以往 2020-11-28 16:26

I want to execute an external command from within my Perl script, putting the output of both stdout and stderr into a $variable of my choice, and to get the com

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 17:25

    A frequently given answer to this question is to use a command line containing shell type redirection. However, suppose you want to avoid that, and use open() with a command and argument list, so you have to worry less about how a shell might interpret the input (which might be partly made up of user-supplied values). Then without resorting to packages such as IPC::Open3, the following will read both stdout and stderr:

    my ($child_pid, $child_rc);
    
    unless ($child_pid = open(OUTPUT, '-|')) {
      open(STDERR, ">&STDOUT");
      exec('program', 'with', 'arguments');
      die "ERROR: Could not execute program: $!";
    }
    waitpid($child_pid, 0);
    $child_rc = $? >> 8;
    
    while () {
      # Do something with it
    }
    close(OUTPUT);
    

提交回复
热议问题