将php脚本作为Linux服务运行

21 浏览
0 Comments

将php脚本作为Linux服务运行

我有一个编写好的 php 脚本,我想在 Linux 中将其作为 service/daemon 运行。

这样我就可以使用命令 service myservice start/stop/restart

我假设它需要放在 /etc/init.d/ 目录下。

0
0 Comments

问题:如何将php脚本作为Linux服务运行?

原因:需要将php脚本作为服务运行,以便在后台持续执行。

解决方法:参考已有的启动脚本,在/etc/init.d目录下可以找到一些现成的脚本,比如httpd。可以参考这些脚本进行修改。

下面是一个示例脚本:

#!/bin/bash
#
# chkconfig: 35 90 12
# description: Foo server
#
# Get function from functions library
. /etc/init.d/functions
# Start the service FOO
start() {
       initlog -c "echo -n Starting FOO server: "
    /path/to/FOO &
    ### Create the lock file ###
    touch /var/lock/subsys/FOO
    success $"FOO server startup"
    echo
}
# Restart the service FOO
stop() {
    initlog -c "echo -n Stopping FOO server: "
    killproc FOO
    ### Now, delete the lock file ###
    rm -f /var/lock/subsys/FOO
    echo
}
### main logic ###
case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
 status)
    status FOO
        ;;
 restart|reload|condrestart)
    stop
    start
    ;;
 *)
    echo $"Usage: $0 {start|stop|restart|reload|status}"
    exit 1
esac
exit 0

在脚本中,可以通过修改`/path/to/FOO`来指定要运行的php文件。可以在脚本中添加检查脚本执行结果的逻辑,通过检查$?的值来确定脚本是否正常运行。

可以参考这篇文章:http://www.cyberciti.biz/tips/linux-write-sys-v-init-script-to-start-stop-service.html,了解更详细的信息。

另外,如果有关于将php脚本作为守护进程运行的问题,可以参考这个链接:http://stackoverflow.com/questions/2036654

0