linux - 如何在初始化脚本中获取 perl 守护进程的 PID?

标签 linux perl daemon

我有以下 perl 脚本:

#!/usr/bin/perl

use strict;
use warnings;
use Proc::Daemon;

Proc::Daemon::Init;

my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };

while ($continue) {
        # stuff
}

我的初始化脚本中有以下内容:

DAEMON='/path/to/perl/script.pl'
start() {
    PID=`$DAEMON > /dev/null 2>&1 & echo $!`
    echo $PID > /var/run/mem-monitor.pid
}

问题是,这返回了错误的 PID!这将返回守护进程运行时启动的父进程的 PID,但该进程会立即被终止。我需要获取子进程的PID!

最佳答案

Proc::Daemon

Proc::Daemon does the following:
...
9. The first child transfers the PID of the second child (daemon) to the parent. Additionally the PID of the daemon process can be written into a file if 'pid_file' is defined. Then the first child exits.

然后,在 new ( %ARGS )

pid_file
Defines the path to a file (owned by the parent user) where the PID of the daemon process will be stored. Defaults to undef (= write no file).

另请参阅 Init() 方法说明。这一切都意味着您可能希望首先使用 new

关键是孙进程是守护进程。然而,childr 传递 pid 并且它可供父级使用。如果在构造函数(守护进程的)中设置了 pid_file => $file_name,则将 pid 写入该文件。


评论要求不要让 shell 脚本依赖于另一个脚本编写的文件。

我可以看到两种方法。

  • 打印由 $daemon->Init() 从父进程返回的 pid,并在 shell 中获取它。这被问题中的重定向打败了,但我不知道为什么需要它们。父子关系在所有设置完成后立即退出,而守护进程与一切分离。

  • Shell 脚本可以使用所需的日志文件名作为参数启动 Perl 脚本,让它通过上述过程将守护程序 pid 写入该文件。该文件仍然由 Perl 输出,但它的作用由 shell 脚本决定。

我想在下面的评论中包含一个声明。我认为这些优于想到的其他两件事:从 shell 保存的配置样式文件中选择文件名更复杂,而解析进程表可能不可靠。

关于linux - 如何在初始化脚本中获取 perl 守护进程的 PID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42292324/

相关文章:

调用属性的 writer 方法的引用时出现 Perl Moose 异常

regex - 正则表达式 : Change syntax from perl to others with grep command

php - exec php 需要很长时间

python - 显示部分搜索结果的最佳实践(当它们来自辅助服务器时,一一显示)

Linux 内核模块,创建后进先出设备

linux - 在终端/Linux 上查找包含特定日期范围文件名的所有文件

perl - 从分隔 block 中解析数据

MySQL General_log 无法启用。我究竟做错了什么?

linux - bash 脚本搜索特定/用户的服务器/然后删除

linux - 保存 zsh 的目录特定历史记录