Bash – Wait multiple process, print exit code if any process get exit

background-processbashshell-script

What I am trying to achieve here is, via script I'm running 3 different custom application in wait simultaneously, if any application get exit, give alert via notify or print exit code.

System in use: Centos 6.8

Best Answer

I thought about Bash's wait -n, but it doesn't let you know which child process exited. How about a simple Perl script?

#!/usr/bin/perl

use strict;
use warnings;
use POSIX ":sys_wait_h";

sub spawn(@) {
    my $pid = fork();
    die "fork: $!" if not defined $pid;
    if ($pid == 0) {
        exec @_ or die "exec: $!";
    }
    return $pid;
}

# Commands to run
my $p1 = spawn '/bin/bash -c "sleep 6; kill $$"';
my $p2 = spawn '/bin/bash -c "sleep 4; exit 4"';

print "spawned PIDs $p1 and $p2\n";

while ((my $child = waitpid(-1, 0)) > 0) {
    my $code = $? >> 8;
    my $status = $? & 0xff;
    printf "child %d finished with exit code %d (status/sig %d)\n", $child, $code, $status;
}
Related Question