有时我的系统调用进入永无止境的状态.为了避免我希望能够在指定的时间后退出呼叫.
有没有办法指定超时限制system?
system("command", "arg1", "arg2", "arg3");
Run Code Online (Sandbox Code Playgroud)
我希望在Perl代码中实现超时以实现可移植性,而不是使用某些特定于操作系统的函数,如ulimit.
这是我的代码,为了清楚起见,删除了错误处理和其他内容:
sub launch_and_monitor {
my ($script, $timeout) = @_;
sub REAPER {
while ((my $child = waitpid(-1, &WNOHANG)) > 0) {}
$SIG{CHLD} = \&REAPER;
}
$SIG{CHLD} = \&REAPER;
my $pid = fork;
if (defined $pid) {
if ($pid == 0) {
# in child
monitor($timeout);
}
else {
launch($script);
}
}
}
Run Code Online (Sandbox Code Playgroud)
launch子程序执行一个shell脚本,然后启动其他进程,如下所示:
sub launch($) {
my ($script) = @_;
my $pid = open(PIPE, "$script|");
# write pid to pidfile
if ($pid != 0) {
while(<PIPE>) {
# do stuff …Run Code Online (Sandbox Code Playgroud)