perlprocessforkstdout

Perl - How to suppress output from a forked child process


I have a perl script which has to make a call to tar within an exec.

exec("tar zcf /tmp/mytarball.gz directoryToTarBall > /dev/null 2>&1" or die ("$!")

This is a child process which I have forked and in the meantime, I'm monitoring the progress of the tar by writing a full stop to STDOUT. The problem I have is that I don't want tar to be verbose when creating the tarball - i dont want output to be echoed to stdout....I just want the progress counter (the full stops) echoing back to screen. I thought I could pass a >/dev/null 2>&1 within the exec command but that didn't work.

Any ideas greatly received. Thanks and regards


Solution

  • Use the exec LIST form to avoid surprises due to shell quoting. This also requires performing the redirection that the shell would do for you.

    use 5.10.0;  # //
    
    my $pid = fork // die "$0: fork: $!";   # / fix Stack Overflow highlighting
    if ($pid) {
      waitpid $pid, 0 or die "$0: waitpid: $!";
      warn "$0: child exited abnormally" if $?;
      print ".\n";  # done!
    }
    else {
      open STDOUT, ">",  "/dev/null" or die "$0: open: $!";
      open STDERR, ">&", \*STDOUT    or exit 1;
      exec "tar", "zcf", "/tmp/mytarball.gz", "directoryToTarBall";
      exit 1;
    }