my $command = 'diskpart'; my (@results) = _timedCommand($command, 30); my $last = pop(@results); if ($last =~ m/^!!!TIMEOUT!!!/i) { print "Bad: \n" . join(' ', @results); } else { push(@results, $last); print "Good:\n " . join(' ', @results); } sub _timedCommand { use threads; use threads::shared; my ($command, $time) = @_; my @results :shared; my $pid :shared; my $thr = async { $pid = open my $fh, "$command |" or die "$!"; @results = <$fh>; $fh->close(); }; while ($thr->is_running() and $time > 0) { sleep(1); $time--; } if ($thr->is_joinable()) { return @results; } else { $thr->detach; kill 3, $pid; push(@results, '!!!TIMEOUT!!!'); print ("\n @results \n"); return @results; } }