my $queue = new Thread::Queue; my $command = 'diskpart'; my $status = _timedCommand($command, 90); if ($status eq 'TIMEOUT') { print "\n=======TIMEOUT==========\n"; } my @ans; while (my $ref = $queue->dequeue_nb()) { if (ref($ref) =~ m/ARRAY/i) { push(@ans, @$ref); } else { push(@ans, $ref); } } print "@ans\n"; sub _timedCommand { my ($command, $time) = @_; my $pid :shared; my @tmp :shared; my $thr = async { $pid = open my $fh, "$command |" or die "$!"; push @tmp, $_ while <$fh>; $fh->close(); }; while ($thr->is_running() and $time > 0) { sleep(1); $time--; } if ($thr->is_joinable()) { $thr->detach(); $queue->enqueue(\@tmp); return 'OK'; } else { $thr->detach; kill 3, $pid; $queue->enqueue(\@tmp); return 'TIMEOUT'; } }