perl - 如何在不杀死 child 的情况下超时waitpid?

标签 perl ipc fork waitpid

我知道很多关于 waitpid 和超时的问题,但它们都通过从警报处理程序中杀死 child 来解决这个问题。

那不是我想要的,我想保持进程运行但从waitpid调度它。

我试图解决的底层问题是一个具有处理队列的主循环的守护进程。一次处理一个任务。

如果任务挂起,则整个主循环挂起。绕过这个 fork()waitpid 似乎是一个显而易见的选择。如果任务挂起,循环仍然挂起。

我可以想到一些我根本不使用 waitpid 的解决方法,但我必须以另一种方式跟踪正在运行的进程,因为我仍然希望一次处理一个任务,同时处理可能挂起的任务。

我什至可以终止任务,但我想让它运行以检查到底出了什么问题。转储一些调试信息的终止处理程序也是可能的。

无论如何,解决该问题的最便捷方法是在可能的情况下使 waitpid 超时。

编辑:

这就是我使用 fork() 和 waitpid 的方式,可能更清楚 child 的含义。

my $pid = fork();

if ($pid == 0){
    # i am the child and i dont want to die
}
elsif ($pid > 0) {
    waitpid $pid, 0;
    # i am the parent and i dont want to wait longer than $timeout
    # for the child to exit
}
else {
    die "Could not fork()";
}

编辑:

使用 waitpid WNOHANG 做我想要的。这种用法是好的做法还是您会以不同的方式使用?
use strict;
use warnings;
use 5.012;
use POSIX ':sys_wait_h';

my $pid = fork();

if ($pid == 0){
    say "child will sleep";
    sleep 20;
    say "child slept";
}
else {
    my $time = 10;
    my $status;
    do {
        sleep 1;
        $status = waitpid -1, WNOHANG;
        $time--;
    } while ($time && not $status );

    say "bye";
}

最佳答案

If a task hangs the whole main loop hangs. To get around this fork() and waitpid seemed an obvious choice. Still if a task hangs the loop hangs.



waitpidWNOHANG 选项一起使用。这样它就不会挂起父进程,并且会在子进程尚未退出时立即返回 0。在您的主循环中,您必须定期轮询所有子项(任务)。

关于perl - 如何在不杀死 child 的情况下超时waitpid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242632/

相关文章:

perl - NGINX 不执行 perl 脚本?

perl - Net::SFTP perl rsa 认证

c - 用户定义信号 sigusr1 和 sigusr2

c - 停止 readline、printf,然后恢复 readline

c - 为什么 fork() 通过 dup2() 关闭文件描述符之一

multithreading - Parallel::ForkManager fork 后只有一个事件线程。为什么?

perl - 如何使我的 Perl 模块的 README 文件与 Github 的 Markdown 显示兼容?

perl - 在perl中对间隔数组进行排序?

node.js - 在 Electron 中堆叠上下文菜单

android 从 AIDL 绑定(bind)服务返回 "live"对象