xref: /openbsd-src/gnu/usr.bin/perl/dist/Time-HiRes/t/Watchdog.pm (revision eac174f2741a08d8deb8aae59a7f778ef9b5d770)
1b8851fccSafresh1package t::Watchdog;
2b8851fccSafresh1
3b8851fccSafresh1use strict;
4b8851fccSafresh1
5b8851fccSafresh1use Config;
6b8851fccSafresh1use Test::More;
7b8851fccSafresh1
8b8851fccSafresh1my $waitfor = 360; # 30-45 seconds is normal (load affects this).
9b8851fccSafresh1my $watchdog_pid;
10b8851fccSafresh1my $TheEnd;
11b8851fccSafresh1
12b8851fccSafresh1if ($Config{d_fork}) {
13*eac174f2Safresh1    note ("I am the main process $$, starting the watchdog process...");
14b8851fccSafresh1    $watchdog_pid = fork();
15b8851fccSafresh1    if (defined $watchdog_pid) {
16b8851fccSafresh1        if ($watchdog_pid == 0) { # We are the kid, set up the watchdog.
17b8851fccSafresh1            my $ppid = getppid();
18*eac174f2Safresh1            note ("I am the watchdog process $$, sleeping for $waitfor seconds...");
19b8851fccSafresh1            sleep($waitfor - 2);    # Workaround for perlbug #49073
20b8851fccSafresh1            sleep(2);               # Wait for parent to exit
21b8851fccSafresh1            if (kill(0, $ppid)) {   # Check if parent still exists
22b8851fccSafresh1                warn "\n$0: overall time allowed for tests (${waitfor}s) exceeded!\n";
23014083a1Safresh1                print("Terminating main process $ppid...\n");
24b8851fccSafresh1                kill('KILL', $ppid);
25*eac174f2Safresh1                note ("This is the watchdog process $$, over and out.");
26b8851fccSafresh1            }
27b8851fccSafresh1            exit(0);
28b8851fccSafresh1        } else {
29*eac174f2Safresh1            note ("The watchdog process $watchdog_pid launched, continuing testing...");
30b8851fccSafresh1            $TheEnd = time() + $waitfor;
31b8851fccSafresh1        }
32b8851fccSafresh1    } else {
33b8851fccSafresh1        warn "$0: fork failed: $!\n";
34b8851fccSafresh1    }
35b8851fccSafresh1} else {
36*eac174f2Safresh1    note ("No watchdog process (need fork)");
37b8851fccSafresh1}
38b8851fccSafresh1
39b8851fccSafresh1END {
40b8851fccSafresh1    if ($watchdog_pid) { # Only in the main process.
41b8851fccSafresh1        my $left = $TheEnd - time();
42014083a1Safresh1        printf("# I am the main process $$, terminating the watchdog process $watchdog_pid before it terminates me in %d seconds (testing took %d seconds).\n", $left, $waitfor - $left);
43b8851fccSafresh1        if (kill(0, $watchdog_pid)) {
44b8851fccSafresh1            local $? = 0;
45b8851fccSafresh1            my $kill = kill('KILL', $watchdog_pid); # We are done, the watchdog can go.
46b8851fccSafresh1            wait();
47014083a1Safresh1            printf("# kill KILL $watchdog_pid = %d\n", $kill);
48b8851fccSafresh1        }
49b8851fccSafresh1        unlink("ktrace.out"); # Used in BSD system call tracing.
50*eac174f2Safresh1        note ("All done.");
51b8851fccSafresh1    }
52b8851fccSafresh1}
53b8851fccSafresh1
54b8851fccSafresh11;
55