【问题标题】:xargs equivalent in perlperl 中的 xargs 等效项
【发布时间】:2014-06-15 07:27:23
【问题描述】:

我喜欢做一些东西,就像 shellscripting 中的 xargs 所做的那样。因此:

  1. 通过exec() 系统调用运行外部命令
  2. 作为子进程
  3. 并行
  4. 等待执行(最好是超时)

在perl中如何实现?

【问题讨论】:

  • 看看Proc::Backgroundtimeout_system() sub。
  • @FilippoLauria 谢谢 - 虽然并行 waiting their exits 他们可能对这个扩展有点棘手,因为wait方法可以在单个后台进程上使用。如果您将其转换为答案,我很乐意接受或/并投票赞成。
  • 在分叉的 pid 中 alarm() 怎么样?
  • @mpapec 是的,即使在循环中我也可以 wait() 。它可能有效,这就是我要做的,虽然它必须更好地自动化,但我的目标也可以通过这种方式实现。
  • xargs 不会并行执行子进程

标签: perl shell exec fork xargs


【解决方案1】:

您可以使用Proc::Background 模块。 特别有趣的是子timeout_system(..)

这是来自Proc::Background 模块页面的示例:

use Proc::Background;
timeout_system($seconds, $command, $arg1);
timeout_system($seconds, "$command $arg1");

my $proc1 = Proc::Background->new($command, $arg1, $arg2);
my $proc2 = Proc::Background->new("$command $arg1 1>&2");
$proc1->alive;
$proc1->die;
$proc1->wait;
my $time1 = $proc1->start_time;
my $time2 = $proc1->end_time;

# Add an option to kill the process with die when the variable is
# DETROYed.
my $opts  = {'die_upon_destroy' => 1};
my $proc3 = Proc::Background->new($opts, $command, $arg1, $arg2);
$proc3    = undef;

【讨论】:

    【解决方案2】:
    my @join;
    push @join, fasync {
      local $SIG{ALRM} = sub { die "alarm\n" };
      alarm 10;
      # exec(..);
      sleep 20;
      print "job1\n";
    };
    push @join, fasync {
    
      print "job2\n";
    };
    
    # wait for jobs
    $_->() for @join;
    
    
    sub fasync(&) {
      my ($worker) = @_;
    
      my $pid = fork() // die "can't fork!";
      if ($pid == 0) {
        $worker->();
        exit(0);
      }
      return sub {
        my ($flags) = @_;
        return waitpid($pid, $flags // 0);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-15
      • 2017-06-26
      • 2013-04-05
      • 2018-06-02
      • 2014-11-06
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 2011-11-13
      相关资源
      最近更新 更多