【问题标题】:How can Perl's `system` proceed without wait for the completion.Perl 的 `system` 怎么能不等待完成而继续。
【发布时间】:2014-05-25 05:20:17
【问题描述】:

在 Perl 中,command 将等待“命令”完成。有没有办法让command 只等待 20 秒?一种情况如下:

command 是一个无限循环,不会结束。 command 将冻结,程序无法继续。我想让程序不被command阻止。

我知道 Ruby 有办法做到这一点。 Perl 有解决方案吗?

谢谢,

=是的

【问题讨论】:

    标签: perl system


    【解决方案1】:

    使用alarm:

    eval {
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm 20;
        system("<Your command>")
        alarm 0;
    };
    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
        # timed out
    }
    else {
        # didn't
    }
    

    【讨论】:

      【解决方案2】:
      #!/usr/bin/perl -w
      use strict;
      use 5.010;
      
      my $foo = 123;
      my $pidChild = fork(); # All objects before this fork statement will be copied.
      given ($pidChild)
      {
          when (!defined($_)) {
              die "Cannot fork: $!";
          }
          when ($_ == 0) {
              # The child process goes here.
              $foo = 456; # This is a duplicate.
              system 'subprocess options'; # Or: exec 'suprocess options';
          }
          default {
              # The original process goes here.
              waitpid($_, 0); # Whether to wait or not is up to you.
              say $foo; # Output: 123
          }
      }
      

      如果需要进程间通信 (IPC),在调用 fork 之前,可以使用内置函数 pipe 创建 2 个处理程序,一个用于输入,另一个用于输出,它们将是由原进程和子进程共享。

      进行 IPC 的方法肯定不止一种。内置函数open、模块IPC::Open2提供的子程序open2和IPC::Open3提供的open3都可以异步运行子进程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-28
        相关资源
        最近更新 更多