gpt4 book ai didi

Perl 超时输出消息

转载 作者:行者123 更新时间:2023-12-01 23:08:09 24 4
gpt4 key购买 nike

我正在编写一个 perl 脚本以使用 Nagios 监控数据库。我正在使用 Time::HiRes 库中的超时警报功能。

use Time::HiRes qw[ time alarm ];
alarm $timeout;

一切正常。问题是我想更改输出消息,因为它返回“Temporizador”,如果我执行

echo $?

返回 142。我想更改消息以生成“exit 3”以便 Nagios 能够识别它。

已经尝试过“eval”但不起作用。

最佳答案

占用时间的函数是用 C 语言编写的,这使您无法安全地使用自定义信号处理程序。

您似乎并不担心强行终止您的程序,所以我建议您使用不带信号处理程序的 alarm 在运行时间过长的情况下强行终止您的程序,并使用包装器来向 Nagios 提供正确的响应。

改变

/path/to/program some args

/path/to/timeout_wrapper 30 /path/to/program some args

下面是timeout_wrapper:

#!/usr/bin/perl
use strict;
use warnings;

use POSIX qw( WNOHANG );
use Time::HiRes qw( sleep time );

sub wait_for_child_to_complete {
my ($pid, $timeout) = @_;
my $wait_until = time + $timeout;
while (time < $wait_until) {
waitpid($pid, WNOHANG)
and return $?;

sleep(0.5);
}

return undef;
}

{
my $timeout = shift(@ARGV);

defined( my $pid = fork() )
or exit(3);

if (!$pid) {
alarm($timeout); # Optional. The parent will handle this anyway.
exec(@ARGV)
or exit(3);
}

my $timed_out = 0;
my $rv = wait_for_child_to_complete($pid, $timeout);
if (!defined($rv)) {
$timed_out = 1;
if (kill(ALRM => $pid)) {
$rv = wait_for_child_to_complete($pid, 5);
if (!defined($rv)) {
kill(KILL => $pid)
}
}
}

exit(2) if $timed_out;
exit(3) if $rv & 0x7F; # Killed by some signal.
exit($rv >> 8); # Expect the exit code to comply with the spec.
}

使用 Nagios Plugin Return Codes .超时实际上应该返回 2

关于Perl 超时输出消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com