首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何知道线程是否在Perl中使用die

如何知道线程是否在Perl中使用die
EN

Stack Overflow用户
提问于 2014-03-04 11:05:59
回答 2查看 177关注 0票数 1

我在一个“主”脚本中创建Perl线程,它通过system调用调用“从”Perl脚本。如果这不好,请随时给我启迪。有时,被调用的从属脚本会失败并出现die。我如何在主脚本中知道这一点,这样我才能杀死主脚本?

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

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

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

此外,系统调用是使用tee完成的,因此这可能是返回值难以获取的部分原因。

system("((" . $cmd . " 2>&1 1>&3 | tee -a $error_log) 3>&1) > $log; echo done | tee -a $log"

EN

回答 2

Stack Overflow用户

发布于 2014-03-04 11:36:42

按照你描述问题的方式,我不认为使用线程是可行的。我更倾向于分叉。无论如何,调用'system‘都是要分叉的。

代码语言:javascript
复制
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 $?;

}
票数 2
EN

Stack Overflow用户

发布于 2014-03-04 11:15:31

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22162049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档