Skip to content

Instantly share code, notes, and snippets.

@tueda
Created June 21, 2014 09:03
Show Gist options
  • Select an option

  • Save tueda/884bf7696af7d559f391 to your computer and use it in GitHub Desktop.

Select an option

Save tueda/884bf7696af7d559f391 to your computer and use it in GitHub Desktop.
system command with a timeout. (Unix only)
# my_system($command, $timeout = 10) [Unix]
sub my_system($;$) {
use POSIX qw(:sys_wait_h);
my $command = $_[0];
my $timeout = $_[1] || 10;
my $pid = fork();
if (!defined($pid)) {
return -1; # failed to fork
}
if ($pid == 0) {
setpgrp();
exec($command);
exit(255); # failed to exec
} else {
while ($timeout > 0) {
my $ret = waitpid($pid, POSIX::WNOHANG);
if ($ret != 0) {
# finished
return $? / 256;
}
$timeout--;
sleep(1);
}
# timeout
kill(-9, getpgrp($pid));
waitpid($pid, 0);
return -2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment