summaryrefslogtreecommitdiffstats
path: root/web/server/h2o/libh2o/share/h2o/kill-on-close
blob: 4890abdf9fbc26e66c5f94b1b757ef6f90a20b2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#! /bin/sh
exec ${H2O_PERL:-perl} -x $0 "$@"
#! perl

use strict;
use warnings;
use Errno qw(EINTR);
use POSIX qw(WNOHANG);

my $rmpath;

while (@ARGV) {
    if ($ARGV[0] eq '--') {
        shift @ARGV;
        last;
    } elsif ($ARGV[0] !~ /^--/) {
        last;
    } elsif ($ARGV[0] =~ /^--rm(?:=(.*)|)$/) {
        shift @ARGV;
        if (defined $1) {
            $rmpath = $1;
        } else {
            die "option `--rm` requires an argument\n"
                unless @ARGV;
            $rmpath = shift @ARGV;
        }
    } else {
        die "unknown argument: $ARGV[0]";
    }
}

shift @ARGV
    if @ARGV && $ARGV[0] eq '--';

die "Usage: $0 [--rm=path] -- cmd args...\n"
    unless @ARGV;

open my $wait_fh, '<&', 5
    or die "failed to open wait file descriptor (fd=5):$!";

my $pid = fork;
die "fork failed:$!"
    if $pid == -1;
if ($pid == 0) {
    exec @ARGV;
    die "failed to exec $ARGV[0]:$!";
}

$SIG{INT} = sub {};

while (1) {
    my $r = sysread $wait_fh, my $buf, 1;
    last if !defined($r) || $r == 0 || ($r == -1 && $! != EINTR);
}

kill 'TERM', $pid;
while (waitpid($pid, 0) != $pid) {
}

if (defined $rmpath) {
    exec '/bin/rm', '-rf', $rmpath;
    die "failed to exec /bin/rm:$!";
}