Skip to content

Instantly share code, notes, and snippets.

@ltriant
Last active March 12, 2019 09:26
Show Gist options
  • Save ltriant/5281a0b9869c8638511c9a2e6f0dc69c to your computer and use it in GitHub Desktop.
Save ltriant/5281a0b9869c8638511c9a2e6f0dc69c 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 Sys::Hostname qw(hostname);
main();
sub main {
announce_myself();
# Any state about the workers is stored in this hash, keyed by pid
my %workers;
foreach my $worker (1 .. 5) {
make_child(\%workers);
}
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 make_child {
my ($worker_state) = @_;
my $pid = fork;
# fork() failed, bail out
if (not defined $pid) {
die "fork(): $!";
}
if ($pid == 0) {
# Child proc runs here
child_main();
exit(0);
}
# Parent proc runs here
my $child_handler = AnyEvent->child(
pid => $pid,
cb => sub {
say "[$$] child $pid died, respawning a new one...";
make_child($worker_state);
delete $worker_state->{$pid};
},
);
$worker_state->{$pid} = {
child_w => $child_handler,
};
}
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