💾 Archived View for thrig.me › blog › 2023 › 08 › 27 › pipewatch.pl captured on 2024-05-26 at 15:50:21.

View Raw

More Information

⬅️ Previous capture (2023-09-08)

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

#!/usr/bin/perl
# pipewatch.pl - react to parent loss via a pipe
use 5.36.0;

# murder proc
{
    my $parent = $;
    my $pid    = fork() // die "fork failed: $!";
    if ( $pid == 0 ) {
        sleep 3;
        warn "kill\t$parent\n";
        kill( KILL => $parent );
        exit;
    }
}

# a child that reacts to the pipe closing
pipe( my $pipe_reader, my $pipe_writer ) or die "pipe failed: $!";
$pipe_reader->blocking(0);

my $pid = fork // die "fork failed: $!";
my $i   = 5;
if ($pid) {
    close $pipe_reader;
    while ( $i-- ) {
        say "parent\t$";
        sleep 1;
    }
} else {
    close $pipe_writer;
    while ( $i-- ) {
        my $ret = sysread $pipe_reader, my $buf, 1;
        die "no parent\n" if defined $ret and $ret == 0;    # EOF
        say "child\t$\t", getppid();
        sleep 1;
    }
    print "\n";
}