代码之家  ›  专栏  ›  技术社区  ›  n-alexander

为什么我从perl的system()开始的进程不是子进程?

  •  4
  • n-alexander  · 技术社区  · 17 年前

    perl的system()启动了一个进程,但破坏了父/子关系?

    PL:

    use POSIX;
    
    system("./test.sh &");
    
    my $pid = `ps -C test.sh -o pid=`;
    
    print "pid: -$pid-\n";
    
    waitpid($pid, 0);
    

    测试:

    while true
    do
        sleep 1
    done
    

    当我运行test.pl时,它会找到并打印test.sh.的正确PID,但是waitpid()返回-1,test.pl退出。test.pl存在后,test.sh仍在运行。

    看起来test.sh不是test.pl的子级,它会中断waitpid()。为什么会发生这种情况,以及如何使System()正常工作?这是因为Perl会自动清除子级吗?如果是,我如何才能解决明确等待孩子的一般任务?

    更新:

    下面的答案建议使用fork/exec。最初的问题是:

    1. 从Perl脚本中,运行启动服务的命令行实用程序。公用设施退出,但服务仍保留。

    2. 一段时间后,找到那个服务的PID并等待它。

    fork/exec并不能解决这个问题,尽管它可以解决这个问题。

    4 回复  |  直到 17 年前
        1
  •  16
  •   Liudvikas Bukys    17 年前

    test.sh进程不是您的子进程。这个 system() 分叉了一个shell(即您的孩子),该shell分叉了一个运行test.sh程序的孩子。是你孩子的壳掉了。

        2
  •  6
  •   Leon Timmermans    17 年前

    你可能想这样做:

    my $pid = fork || exec './test.sh';
    print "pid: -$pid-\n";
    waitpid($pid, 0);
    

    虽然shell脚本处于无限循环中,但它将永远等待。

        3
  •  6
  •   jrockway    17 年前

    一般来说,如果不希望Perl提供帮助,则应该手动fork和exec 你出去。很难确定你到底在做什么,但我 你想这样做:

    my $pid = fork;
    unless($pid){
        # child;
        exec(qw/sh test.sh/);
    }
    
    # parent
    ...
    waitpid $pid, 0;
    

    就我个人而言,我更喜欢让任何活动保姆:

    my $done = AnyEvent->condvar;
    
    my $pid = fork;
    
    unless( $pid ) { ... }
    
    my $w = AnyEvent->child (
       pid => $pid,
       cb  => sub {
          my ($pid, $status) = @_;
          warn "pid $pid exited with status $status";
          $done->send;
       },
    );
    
    $done->recv; # control resumes here when child exits
    

    或者更一般地说: http://github.com/jrockway/anyevent-subprocess/tree/master

        4
  •  5
  •   aks    17 年前

    进一步解释刘德维卡的回答-

    system("./test.sh &")
     |
     |--> (P) /bin/sh (to run test.sh)
           |
           |--> (P) test.sh & (still running)
    
    (P) - process
    

    在fork ing并运行test.sh脚本之后,/bin/sh shell(Perl系统调用的子级)将退出,从而从waitpid()中获得-1返回值。