在 perl 中启动 bash 命令的超时时间 [英] Timeout for launching a bash command in perl

查看:149
本文介绍了在 perl 中启动 bash 命令的超时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我必须从 perl 触发 bash 命令,并需要该命令在指定的超时内退出目前我正在使用这个模块

I have a usecase where I have to fire a bash command from perl and need that command to exit within a specified timeout Currently I am using this moudle

use System::Timeout qw(timeout);
timeout(10, "my bash script")

(由于需要超时,我没有使用 system() 进行调用)

(As timeout is necessary I am not using system() to make the call)

如果 shell 脚本以非零退出代码退出或命令超时,则此函数返回 1.

This function returns 1 if shell script exitted with non-zero exit code or the command timed out.

问题

  1. 此函数根据传递或失败的命令仅返回 1/0(我需要 bash 脚本的确切退出代码)
  2. 如果它是 1,我不知道脚本是否以非零退出代码退出或有超时(区分超时和 shell 脚本失败)
  3. 被调用进程的pid未知(所以如果scipt由于超时而失败,我需要杀死它)

满足上述两个条件对我来说很重要(我非常了解如何在 python 中执行此操作,但无法获得 perl 的解决方案)

It is important for me to satisfy both of the above criteria(I know very well how to do this in python, but could not get a solution for perl)

我不知道在 perl 中 fork 当前进程然后用 SIGALRM 监视它是否会有所帮助(分叉会给我分叉进程的pid,而不是我从那个分叉启动的bash脚本.是否会杀死分叉,也会杀死它启动的bash进程?)

I do not know if forking a current process in perl and then monitoring it with SIGALRM will help (Forking will give me pid of the forked process and NOT the bash script which I have launched from that fork. Will killing the fork, also kill the bash process it launched?)

感谢您的帮助

推荐答案

您的系统可能有 gnu timeout 命令,如果它使用超时杀死子进程并返回否则命令退出代码.如果您没有 gnu timeout,您确实提到您有 bash,这意味着您可以使用我的 bash 模拟器进行 gnu timeout, https://github.com/ronaldxs/bash-timeout,我很乐意期待任何反馈.查看 System::Timeout 的源代码,它基于 CPAN 模块 IPC::Cmd,建议将以下内容作为另一个起点:

Your system might have the gnu timeout command which sets an exit code of 124 if it kills the child process with timeout and returns the command exit code otherwise. If you don't have gnu timeout, you did mention you have bash which means you could use my bash emulator for gnu timeout, https://github.com/ronaldxs/bash-timeout, and I would happily look forward to any feedback. Looking at the source code for System::Timeout, it is based on CPAN module IPC::Cmd which suggests the following as another starting point:

#!/usr/bin/env perl

use Modern::Perl;
use Data::Dump;

use IPC::Cmd 'run_forked';

my $rc = run_forked('sleep 5; exit 3', { timeout => 2 });

dd $rc;

输出:

{
  child_pgid       => 69066,
  err_msg          => "ran more than [2] seconds\n",
  exit_code        => 0,
  ...
  timeout          => 2,
}

这篇关于在 perl 中启动 bash 命令的超时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆