Question

I liked to make something, what xargs in shellscripting does. Thus:

  1. Running external commands by the exec() system calls
  2. as child processes
  3. parallel
  4. waiting their execution (ideally with a timeout)

How can it be done in perl?

Was it helpful?

Solution

You could use the Proc::Background module. Particularly interesting is the sub timeout_system(..).

Here's an example coming from the Proc::Background module page:

use Proc::Background;
timeout_system($seconds, $command, $arg1);
timeout_system($seconds, "$command $arg1");

my $proc1 = Proc::Background->new($command, $arg1, $arg2);
my $proc2 = Proc::Background->new("$command $arg1 1>&2");
$proc1->alive;
$proc1->die;
$proc1->wait;
my $time1 = $proc1->start_time;
my $time2 = $proc1->end_time;

# Add an option to kill the process with die when the variable is
# DETROYed.
my $opts  = {'die_upon_destroy' => 1};
my $proc3 = Proc::Background->new($opts, $command, $arg1, $arg2);
$proc3    = undef;

OTHER TIPS

my @join;
push @join, fasync {
  local $SIG{ALRM} = sub { die "alarm\n" };
  alarm 10;
  # exec(..);
  sleep 20;
  print "job1\n";
};
push @join, fasync {

  print "job2\n";
};

# wait for jobs
$_->() for @join;


sub fasync(&) {
  my ($worker) = @_;

  my $pid = fork() // die "can't fork!";
  if ($pid == 0) {
    $worker->();
    exit(0);
  }
  return sub {
    my ($flags) = @_;
    return waitpid($pid, $flags // 0);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top