user3921905
user3921905

Reputation: 129

run php script in background and never die 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

Upvotes: 0

Views: 3059

Answers (2)

wormi4ok
wormi4ok

Reputation: 632

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)

Upvotes: 2

hardillb
hardillb

Reputation: 59731

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

Upvotes: 1

Related Questions