💾 Archived View for thrig.me › blog › 2023 › 08 › 27 › bad.pl captured on 2024-05-10 at 12:21:16.

View Raw

More Information

⬅️ Previous capture (2023-09-08)

-=-=-=-=-=-=-

#!/usr/bin/perl
# bad.pl - a not so good way to check if the parent has gone away
use 5.36.0;

# murder proc - kills the parent after a few seconds
{
    my $pid = fork() // die "fork failed: $!";
    if ( $pid == 0 ) {
        my $parent = getppid();    # NOTE race condition!
        sleep 3;
        warn "kill\t$parent\n";
        kill( KILL => $parent );
        exit;
    }
}

# a child process that reacts to parent being killed. maybe.
my $pid = fork() // die "fork failed";
if ($pid) {
    sleep 99;    # parent will not go gently into that good night
} else {
    my $i = 5;
    while ( $i-- ) {
        my $parent = getppid();    # NOTE race condition!
        die "parent went away!\n" if $parent == 1;
        warn "parent $parent\n";
        sleep 1;
    }
    print "\n";
}