Skip to content

Instantly share code, notes, and snippets.

@ltriant
Last active March 12, 2019 09:26
Show Gist options
  • Save ltriant/e7a3c1487752b9ce77df563fe03ddd6e to your computer and use it in GitHub Desktop.
Save ltriant/e7a3c1487752b9ce77df563fe03ddd6e to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use v5.10;
use warnings;
use strict;
use EV;
use AnyEvent;
use POSIX qw();
use Sys::Hostname qw(hostname);
main();
sub main {
announce_myself();
my $sigset = POSIX::SigSet->new;
my $signal = POSIX::SigAction->new(\&sigchld_handler, $sigset, POSIX::SA_NODEFER);
POSIX::sigaction(POSIX::SIGCHLD, $signal);
foreach my $worker (1 .. 5) {
make_child();
}
say "[$$] new parent here, looking after children for the rest of my life";
AnyEvent->condvar->recv;
}
sub announce_myself {
my $hostname = hostname();
say "[$$] announcing myself to service discovery";
# Imagine there's more code here to announce this host with
# service discovery
}
sub sigchld_handler {
while (1) {
my $kid = waitpid(-1, POSIX::WNOHANG);
if ($kid <= 0) {
last;
}
say "[$$] child $kid died, respawning a new one...";
make_child();
}
}
sub make_child {
my $pid = fork;
# fork() failed, bail out
if (not defined $pid) {
die "fork(): $!";
}
if ($pid == 0) {
# Child proc runs here
child_main();
exit(0);
}
}
sub child_main {
say " [$$] child ready, randomly doing stuff";
while (1) {
sleep(rand(10));
# Imagine some real work is being done here, instead of
# sleeping for random periods of time
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment