Skip to content

Instantly share code, notes, and snippets.

@sherwind
Created November 8, 2018 03:39
Show Gist options
  • Save sherwind/973deabce1023c59c85e1249b7d385e1 to your computer and use it in GitHub Desktop.
Save sherwind/973deabce1023c59c85e1249b7d385e1 to your computer and use it in GitHub Desktop.
run_many
#!/usr/bin/env perl
# run a command many times for a number of times at a time
# by Sherwin Daganato, 20100414
# based on runN.pl which has the copyright:
# Copyright 2007 Mark Jason Dominus <[email protected]>
# Modified by Aaron Crane; see http://aaroncrane.co.uk/2008/07/runN/
use strict;
use warnings;
use Getopt::Std qw<getopts>;
sub usage {
warn <<'EOF';
Usage: run_many [OPTIONS] COMMAND
Run a command many times for a number of times at a time
Options:
-n TIMES
Run this many times (default: 1)
-j JOBS
Run this many jobs in parallel (default: 1)
Example:
run_many -n 100 -j 10 bash -c 'date; sleep 5'
EOF
exit 1;
}
my %opt = (j => 1, n => 1);
getopts('j:n:', \%opt) or usage();
usage() if !@ARGV;
my @args = @ARGV;
my %pid;
my $exit_status = 0;
for (my $i = 0; $i < $opt{n}; $i++) {
wait_for_child() while keys %pid >= $opt{j};
$pid{ spawn(@args) } = 1;
}
1 while wait_for_child();
exit $exit_status;
sub wait_for_child {
my $child = wait;
$exit_status = 1 if $? != 0;
return if $child < 0;
delete $pid{$child};
return 1;
}
sub spawn {
my (@args) = @_;
my $pid = fork;
die "can't fork $args[0]: $!\n" if !defined $pid;
return $pid if $pid;
exec { $args[0] } @args
or die "can't exec $args[0]: $!\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment