在后台运行php脚本,永远不会死linux

时间:2017-04-13 06:17:26

标签: php linux process mqtt

我有一个使用Mosquitto客户端的PHP脚本。我使用putty SSH访问服务器。我想连续在后台运行php脚本,即使我从putty断开连接。我已经尝试过屏幕和nohup但是在关闭putty窗口时会停止

谢谢

2 个答案:

答案 0 :(得分:1)

一个简单的解决方案是

nohup php script.php &

因此,您在后台运行脚本并断开进程与终端的连接。如果没有帮助,请在其后尝试disown命令。这些命令之间存在good answer with detailed explanation的差异。

要完全控制您的脚本,一个很好的选择是System V init脚本。您可以使用https://github.com/fhd/init-script-template处的模板。

将模板复制到/etc/init.d目录并重命名。在模板中,您需要更改变量:

dir="/your/working/directory"
cmd="nohup php script.php"
user="your user"

这样做可以通过

控制脚本
/etc/init.d/your_script start
/etc/init.d/your_script stop

确保您有权使用/var/log//var/run/进行撰写,或以sudo运行脚本(将user=""留空)

答案 1 :(得分:0)

使用screen是比nohup更好的解决方案。

屏幕让你命名会话并稍后重新加入它们,这样你就不需要使用ps来找到你的后台应用程序了

您可以像这样开始一个名为screen的会话

screen -S [session name]

您可以使用 ctrl - a d 分离,然后重新附加

screen -r [session name]

您还可以使用

在后台使用命令启动会话
screen -dmS [session name] [command]

https://www.gnu.org/software/screen/manual/screen.html