#!/usr/bin/env perl
#
# runN [-n N] CMD ARGS... - run up to N CMD in parallel command with ARGS
#
# ---
# see: https://perl.plover.com/classes/mybin/samples/slide147.html
# source: https://leahneukirchen.org/dotfiles/bin/runN

use Getopt::Std;
my %opt = ( n => 1 );
getopts( 'n:v', \%opt ) or usage();

sub spawn {
    my $pid = fork;
    die "fork: $!" unless defined $pid;
    return $pid if $pid;
    warn "@_\n" if $opt{v};
    exec @_;
    die "exec: $!";
}

my @cmd = split /\s+/, shift;

my %pid;
while (@ARGV) {
    if ( keys(%pid) < $opt{n} ) {
        $pid{ spawn( @cmd, shift @ARGV ) } = 1;
    }
    else {
        delete $pid{ wait() };
    }
}

1 while wait() >= 0;
