且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Linux 中将 Perl 脚本作为系统守护进程运行?

更新时间:2023-02-22 21:02:58

最简单的方法是使用 Proc::Daemon.

The easiest way is to use Proc::Daemon.

#!/usr/bin/perl

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

Proc::Daemon::Init;

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

while ($continue) {
     #do stuff
}

或者,您可以执行 Proc::Daemon 所做的所有事情:

Alternately you could do all of the things Proc::Daemon does:

  1. fork 一个子进程并退出父进程.
  2. 成为会话负责人(将程序与控制终端分离).
  3. fork 另一个子进程并退出第一个子进程.这可以防止获得控制终端的可能性.
  4. 将当前工作目录更改为"/".
  5. 清除文件创建掩码.
  6. 关闭所有打开的文件描述符.

与运行级别系统集成很容易.您需要一个如下所示的脚本(将 XXXXXXXXXXXX 替换为 Perl 脚本的名称,将 YYYYYYYYYYYYYYYYYY 替换为它的功能描述,以及 /path/to> 带有 Perl 脚本的路径)在 /etc/init.d 中.由于您使用的是 CentOS,一旦您在 /etc/init.d 中拥有脚本,您就可以使用 chkconfig 在各种运行级别中将其关闭或打开.

Integrating with the runlevel system is easy. You need a script like the following (replace XXXXXXXXXXXX with the Perl script's name, YYYYYYYYYYYYYYYYYYY with a description of what it does, and /path/to with path to the Perl script) in /etc/init.d. Since you are using CentOS, once you have the script in /etc/init.d, you can just use chkconfig to turn it off or on in the various runlevels.

#!/bin/bash
#
# XXXXXXXXXXXX This starts and stops XXXXXXXXXXXX
#
# chkconfig: 2345 12 88
# description: XXXXXXXXXXXX is YYYYYYYYYYYYYYYYYYY
# processname: XXXXXXXXXXXX
# pidfile: /var/run/XXXXXXXXXXXX.pid
### BEGIN INIT INFO
# Provides: $XXXXXXXXXXXX
### END INIT INFO

# Source function library.
. /etc/init.d/functions

binary="/path/to/XXXXXXXXXXXX"

[ -x $binary ] || exit 0

RETVAL=0

start() {
    echo -n "Starting XXXXXXXXXXXX: "
    daemon $binary
    RETVAL=$?
    PID=$!
    echo
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/XXXXXXXXXXXX

    echo $PID > /var/run/XXXXXXXXXXXX.pid
}

stop() {
    echo -n "Shutting down XXXXXXXXXXXX: "
    killproc XXXXXXXXXXXX
    RETVAL=$?
    echo
    if [ $RETVAL -eq 0 ]; then
        rm -f /var/lock/subsys/XXXXXXXXXXXX
        rm -f /var/run/XXXXXXXXXXXX.pid
    fi
}

restart() {
    echo -n "Restarting XXXXXXXXXXXX: "
    stop
    sleep 2
    start
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    status)
        status XXXXXXXXXXXX
    ;;
    restart)
        restart
    ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
    ;;
esac

exit 0