如何在Linux中将Perl脚本作为系统守护程序运行? [英] How can I run a Perl script as a system daemon in linux?
问题描述
让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所做的所有事情:
Alternately you could do all of the things Proc::Daemon does:
- 派生一个孩子并退出父流程.
- 成为会话负责人(将程序与控制终端分离).
- 分叉另一个子进程并退出第一个子进程.这样可以避免获得控制终端的可能性.
- 将当前工作目录更改为
"/"
. - 清除文件创建掩码.
- 关闭所有打开的文件描述符.
- Fork a child and exits the parent process.
- Become a session leader (which detaches the program from the controlling terminal).
- Fork another child process and exit first child. This prevents the potential of acquiring a controlling terminal.
- Change the current working directory to
"/"
. - Clear the file creation mask.
- Close all open file descriptors.
与运行级别系统集成很容易.您需要在/etc/init.d
中使用类似以下的脚本(将XXXXXXXXXXXX
替换为Perl脚本的名称,将YYYYYYYYYYYYYYYYYYY
替换为其功能的描述,并将/path/to
替换为Perl脚本的路径).由于使用的是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屋!