【问题标题】:How to know if a thread uses die in Perl如何知道一个线程是否在 Perl 中使用 die
【发布时间】:2014-03-04 03:05:59
【问题描述】:

我正在通过system 调用调用“从属”perl 脚本的“主”脚本中创建 Perl 线程。如果这很糟糕,请随时启发我。有时被调用的从脚本会失败并且die。如何在主脚本中知道这一点,以便我可以杀死主?

有没有办法可以向主线程返回一条消息,指示从属线程已正确完成?我知道在线程中使用 exit 并不是一个好习惯。请帮忙。

================================================ ==================================== 编辑:

为了澄清,我有大约 8 个线程,每个线程运行一次。它们之间存在依赖关系,因此我设置了阻止某些线程在初始线程完成之前运行的障碍。

系统调用也是使用tee 完成的,因此这可能是难以获得返回值的部分原因。
system("((" . $cmd . " 2>&1 1>&3 | tee -a $error_log) 3>&1) > $log; echo done | tee -a $log"

【问题讨论】:

    标签: multithreading perl


    【解决方案1】:

    您描述问题的方式,我不认为使用线程是要走的路。我会更倾向于分叉。无论如何,调用“系统”都会分叉。

    use POSIX ":sys_wait_h";
    
    my $childPid = fork();
    if (! $childPid) {
        # This is executed in the parent
        # use exec rather than system, so that the child process is replaced, rather than
        # forking a new subprocess (or maybe even shell) to run your child process
        exec("/my/child/script") or die "Failed to run child script: $!";
    }
    
    # Code here is executed in the parent process
    # you can find out what happened to the parent process by calling wait
    # or waitpid. If you want to be able to continue processing in the
    # parent process then call waitpid with second argument WNOHANG
    
    # EG. inside some event loop, do this
    if (waitpid($childPid, WNOHANG)) {
    
        # $? now contains the exit status of child process
        warn "Child had a problem: $?" if $?;
    
    }
    

    【讨论】:

    • 我选择使用线程的主要原因是因为我有依赖关系,并且某些工作需要障碍。这可以用fork完成吗?我对 Perl 中的多线程知之甚少。
    • 有没有办法让从属线程使用system向主线程返回一个值?
    【解决方案2】:

    可能有一个 CPAN 模块非常适合您正在尝试做的事情。也许Proc::Daemon - Run Perl program(s) as a daemon process.

    【讨论】:

      猜你喜欢
      • 2012-10-03
      • 2019-07-21
      • 2010-10-28
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      相关资源
      最近更新 更多