如何在 Linux 中将 Perl 脚本作为系统守护进程运行? [英] How can I run a Perl script as a system daemon in linux?

查看:37
本文介绍了如何在 Linux 中将 Perl 脚本作为系统守护进程运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让 Perl 脚本在 Linux 中作为守护程序运行的简单方法是什么?

What's a simple way to get a Perl script to run as a daemon in linux?

目前,这是在 CentOS 上.我希望它随系统启动并随系统关闭,所以一些 /etc/rc.d/init.d 集成也很好,但我总是可以添加自定义行/etc/rc.d/rc.local.

Currently, this is on CentOS. I'd want it to start up with the system and shutdown with the system, so some /etc/rc.d/init.d integration would also be nice, but I could always add a custom line to /etc/rc.d/rc.local.

推荐答案

最简单的方法是使用 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

这篇关于如何在 Linux 中将 Perl 脚本作为系统守护进程运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆