gpt4 book ai didi

perl - 使 perl 命令超时

转载 作者:行者123 更新时间:2023-12-01 23:48:51 25 4
gpt4 key购买 nike

我正在使用未安装 coreutils(timeout) 工具的旧 Solaris 节点。我正在尝试打印由 "-"x 80 字符分隔的三个 bash 命令的输出。其中一个命令的表现很差,需要很长时间,我需要使该命令超时并打印剩余的输出。我正在尝试使用 alarm shift 但这没有帮助。

我需要将命令保留为一行,因为我需要在 ansible 的 shell 模块中使用此命令。有人可以帮忙吗。

如果我在 bash 终端上运行不同的 CMDn 命令,它会返回以下输出:

This is
from CMDn

其中 n 是 0 到 3。

当我运行以下 perl 命令时,它返回:

perl -sanle 'BEGIN{$sep=("-"x80)."\n"; \
print "$sep $CMD0\n $sep $CMD1\n $sep $CMD2\n $sep $CMD2flt\n";exit}' \
-- -CMD0="$(CMD0)" -CMD1="$(CMD1 -q all)" -CMD2="$(CMD2)" -CMD2flt="$(CMD3)"


--------------------------------------------------------------------------------
This is
from CMD0

--------------------------------------------------------------------------------
This is
from CMD1

--------------------------------------------------------------------------------
This is
from CMD2

--------------------------------------------------------------------------------
This is
from CMD3

有时,CMD3 需要很长时间,我需要暂停它并继续打印 CMD0CMD1命令2。我尝试了这个命令,但这没有帮助,因为它没有超时并且所有输出都会超时。在此示例中,我将 sleep 15 && CMD3 用作 CMD3 并将超时用作 10 ,但这没有帮助。我关注了这篇文章 Timeout command on Mac OS X?

perl -sanle 'BEGIN{alarm shift; $sep=("-"x80)."\n"; \
print "$sep $CMD0\n $sep $CMD1\n $sep $CMD2\n $sep $CMD2flt\n";exit}' \
-- -CMD0="$(CMD0)" -CMD1="$(CMD1 -q all)" -CMD2="$(CMD2)" -CMD2flt="$(sleep 15 && CMD3)" 10

如果(例如)CMD3 超时,则期待以下输出。

--------------------------------------------------------------------------------
This is
from CMD0

--------------------------------------------------------------------------------
This is
from CMD1

--------------------------------------------------------------------------------
This is
from CMD2

--------------------------------------------------------------------------------
Null or blank or any intuitive text

最佳答案

alarm 在这里帮不了你。命令行上的表达式 -CMD2flt="$(CMD3)"CMD3 的输出扩展到 before perl 脚本启动的变量.

幸运的是,很容易在 perl 中创建您自己的 timeout 脚本。

#! perl
# timeout N cmd [arg1 [arg2 [...]]]
# execute cmd [arg1 [...]] and timeout after N seconds
$N = shift;
$pid = $$;
fork || exec($^X,"-e","sleep 1,kill(0,$pid) || exit for 1..$N;kill -9,$pid");
exec(@ARGV);

(第一个 exec 调用中的代码是穷人的警报。它将监视调用进程 [进程 ID $pid] 最多 $N秒后发送一个kill信号。比Perl的alarm更有效,它可能无法终止所有的系统调用或外部命令)。

-CMD2flt=$(CMD3) 替换为 -CMD2filt=$($HOME/bin/timeout 30 CMD3) 就可以了。

关于perl - 使 perl 命令超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63748207/

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