#!/usr/bin/env perl # for https://perlmonks.org/?node_id=1231710 # author: bliako # 27/03/2019 # WARNING: it writes and deletes file 'xyz' in local dir use strict; use warnings; sub spawner { my ($cmd, $timeout) = @_; print "spawner starting.\n"; my $pid = fork(); if( ! $pid ){ print "spawner in child.\n"; eval { local $SIG{ALRM} = sub { die "alarm blah blah" }; alarm $timeout; print "starting system command.\n"; `$cmd`; print "system command ended.\n"; alarm 0; }; if( $@ =~ /^alarm blah blah/ ){ die "spawner: child timed out" } elsif( $@ ){ die "spawner: something wrong with eval block which spawns '$cmd'" } exit 0; } print "spawner ending.\n"; } spawner('rm -f xyz; sleep 5; touch xyz', 2); wait(); if( -e 'xyz' ){ print "command seems to have terminated on its own will.\n"; } else { print "command has timed out.\n"; }