doubingqi5829
2017-04-13 06:17 阅读 138
已采纳

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

I have a php script that use Mosquitto client. I am using putty SSH to access to the server. I want to run the php script in background continously even when I disconnect from putty. I have tried screen and nohup but it stop when closing putty window

Thank you

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    drqvsx1228 drqvsx1228 2017-04-13 06:49

    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. 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. There is a template at https://github.com/fhd/init-script-template, which you can use.

    Copy template to /etc/init.d directory and rename it. 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)

    点赞 评论 复制链接分享
  • drmcm84800 drmcm84800 2017-04-13 08:25

    Using screen is a much better solution than 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

    You can start a named screen session like this

    screen -S [session name]
    

    Which you can detach from with ctrl-a,d then reattach with

    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

    点赞 评论 复制链接分享

相关推荐