Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing progress whilst running a system() command in Perl

Tags:

perl

I have a Perl script which performs some tasks, one of which is to call a system command to "tar -cvf file.tar.....".

This can often take some time so I'd like the command line to echo back a progress indicator, something like a # echoing back to screen whilst the system call is in progress.

I've been doing some digging around and stumbled across fork. Is this the best way to go? Is it possible to fork off the system command, then create a while loop which checks on the staus of the $pid returned by the fork?

I've also seen references to waitpid.... I'm guessing I need to use this also.

fork system("tar ... ")
while ( forked process is still active) {
    print #
    sleep 1
}

Am I barking up the wrong tree?

Many thanks John

like image 509
john Avatar asked Jul 07 '10 08:07

john


1 Answers

Perl has a nice construction for this, called "pipe opens." You can read more about it by typing perldoc -f open at a shell prompt.

# Note the use of a list for passing the command. This avoids
# having to worry about shell quoting and related errors.
open(my $tar, '-|', 'tar', 'zxvf', 'test.tar.gz', '-C', 'wherever') or die ...;

Here's a snippet showing an example:

  open(my $tar, '-|', 'tar', ...) or die "Could not run tar ... - $!";
  while (<$tar>) {
       print ".";
  }
  print "\n";
  close($tar);

Replace the print "." with something that prints a hash mark every 10 to 100 lines or so to get a nice gaugebar.

like image 162
Johan Avatar answered Nov 30 '22 20:11

Johan