简体   繁体   English

在后台运行php脚本,永不死于Linux

[英]run php script in background and never die linux

I have a php script that use Mosquitto client. 我有一个使用Mosquitto客户端的php脚本。 I am using putty SSH to access to the server. 我正在使用腻子SSH访问服务器。 I want to run the php script in background continously even when I disconnect from putty. 我想在后台连续运行php脚本,即使我与腻子断开连接也是如此。 I have tried screen and nohup but it stop when closing putty window 我已经尝试过屏幕和nohup,但是在关闭腻子窗口时它停止了

Thank you 谢谢

A simple solution is 一个简单的解决方案是

nohup php script.php &

So you run script in background and disconnect the process from the terminal. 因此,您可以在后台运行脚本,并断开与终端的连接。 If it doesn't help, try disown command after it. 如果没有帮助,请尝试在其后disown命令。 There is a good answer with detailed explanation of differences between these commands. 有一个很好的答案,其中详细解释了这些命令之间的差异。

To get full control of your script, a good choice would be a System V init script. 要完全控制您的脚本,一个不错的选择是System V初始化脚本。 There is a template at https://github.com/fhd/init-script-template , which you can use. 您可以使用https://github.com/fhd/init-script-template上的模板。

Copy template to /etc/init.d directory and rename it. 将模板复制到/etc/init.d目录并重命名。 In template you need to change variables: 在模板中,您需要更改变量:

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

Doing that you will be able to control your script by 这样,您将可以通过以下方式控制脚本

/etc/init.d/your_script start
/etc/init.d/your_script stop

Make sure you have permissions to write in /var/log/ and /var/run/ , or run script as sudo (leave user="" empty) 确保您有权在/var/log//var/run/ ,或以sudo身份运行脚本(将user=""空)

Using screen is a much better solution than nohup. 使用screen比nohup更好。

screen let's you name sessions and rejoin them later so you don't need to resort to using ps to find your backgrounded applications 屏幕上,您可以命名会话并稍后重新加入,因此您无需诉诸于使用ps查找后台应用程序

You can start a named screen session like this 您可以像这样开始命名的screen会话

screen -S [session name]

Which you can detach from with ctrl - a , d then reattach with 您可以使用ctrl - ad分离,然后使用

screen -r [session name]

You can also start a session with a command in the background with 您还可以在后台使用命令启动会话

screen -dmS [session name] [command]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM