在 apache2 启动时启动 php 脚本

Launch php script at apache2 startup

我正在尝试 运行 一个 php 脚本来在服务器崩溃、重新启动或其他情况下恢复状态。 因为 php 脚本需要数据库 运行 我首先尝试通过在 init.d 中创建一个文件来 运行 连接它,但没有用,它只是在需要时启动。 所以现在我认为这是 运行 描述的 here 脚本在 apache2 启动时最简单的方法。 所以目前我已经将 php -q /var/www/scripts/testing.php & ;; 添加到 /etc/init.d/apache2 中的 do_start(),如下所示:

do_start()
{
        # Return
        #   0 if daemon has been started
        #   1 if daemon was already running
        #   2 if daemon could not be started

        if pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                return 1
        fi

        if apache_conftest ; then
                $APACHE2CTL start
                php -q /var/www/scripts/testing.php &
                ;;
                apache_wait_start $?
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed."
                return 2
        fi
}

但是因为这根本不起作用,所以我还在 link 中提到的 restart) 部分添加了这个 php 执行。这看起来像这样:

 restart)
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop stop
        case "$?" in
                0|1)
                        do_start
                        case "$?" in
                                0)
                                        log_end_msg 0
                                        ;;
                                1|*)
                                        log_end_msg 1 # Old process is still or failed to running
                                        print_error_msg
                                        exit 1
                                        ;;
                        esac
                        ;;
                *)
                        # Failed to stop
                        log_end_msg 1
                        print_error_msg
                        exit 1
                        ;;
        php -q /var/www/scripts/testing.php &
        ;;
        esac
        ;;

但脚本仍然不是 运行。 php 脚本如下所示:

<?php
file_put_contents('/var/www/html/log', "301,$timestamp,Recreating all connections after restart,N/A\n",FILE_APPEND);
?>

因为我希望它尽可能简单,但是日志文件仍然是空的。我愿意接受任何解决我问题的想法。

p.s.: 我已经尝试通过 /etc/systemd/system/ 中的一项服务来做到这一点,但是由于我正在启动一个应该持久的连接,所以我必须使用 [=19] =]、nohupdisown。我已经尝试了这三个,但都没有用,它们只是没有启动脚本。 (当时是 bash,我切换到 php 以便能够从 apache2 文件中 运行 它)

你不应该使用 apache 来启动你的脚本,而是按照你的第一个想法使用自己的 init-script 除非你的 php 脚本依赖于 apache 的存在。

只需将 shell 脚本 callmyphp 放入 /etc/init.d 中,调用 php 解释器并将您的 php 脚本作为参数传递,例如:

#!/bin/sh
/usr/bin/php -q /path/to/myphp.php

不要忘记使用 chmod 755 /etc/init.d/callmyphp 来执行调用脚本。

然后通过符号链接将您的调用脚本添加到所需的 运行 级别,即通过 运行ning update-rc.d callmyphp defaults

另见 https://debian-administration.org/article/28/Making_scripts_run_at_boot_time_with_Debian