Link to home
Start Free TrialLog in
Avatar of condor888
condor888

asked on

How to run a server as a backend service on Raspberry Pi

Sometimes when I run a server such as mosquitto
mosquitto -c /etc/mosquitto/mosquitto.conf

Open in new window

or Flask
python app.py

Open in new window

, it is only running when the terminal which is running the ssh is alive.
1. Is there a way to run it on the background no matter the terminal is shutdown or not? (Rebooting is not considered)
2. What if I want it to automatically start when the Pi reboot?

Thanks!
Avatar of Chris Millard
Chris Millard
Flag of United Kingdom of Great Britain and Northern Ireland image

put the command in /etc/rc.local
Avatar of noci
noci

Best is to make a service description, see examples in /etc/init.d/...
lots of start scripts, they can also be started on systemd based systems

if you put a command in rc.local then please do it as follows:

python whatever.py </dev/null >/dev/null 2>&1 &
or
mosquitto -c /etc/mosquitto.conf </dev/null >/dev/null 2>&1 &

(or 2> /var/log/servicename.log in place of 2>&1 to get a logging of stderr).
Avatar of condor888

ASKER

@noci and @reredok, what is the difference between /etc/rc.local and /etc/profile?

Also do i need sudo before python xxx?
Run a Script after login: /etc/profile
Run a script on start up: /etc/rc.local Reference
ASKER CERTIFIED SOLUTION
Avatar of Kent W
Kent W
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@mugojava, I am getting confused. Then what is the difference between
nohup ping www.google.com &

Open in new window

and
ping www.google.com &

Open in new window

? Thanks!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And there are unices where the TTY driver sends a sighup to all processes that are associated with that terminal, when the last channel to the tty closes (ie. a process logs off, a modem disconnects etc. etc.)
hence the name SIGHUP, SIG Hangup...

that is why </dev/null & >/dev/null is needed.
@mugojava, it turns out that on my pi, it is "huponexit off" and a simple "python app.py &" works. Thanks!
Nice. I'm glad it worked for ya.
Sorry about the late feedback. But I found a weird thing, which is when I run "python app.py &" under the python virtualenv. I can see two processes running "python app.py" (please see attached). Do you know what is going on?

FYI, I put this "source /home/pi/virtualenv/flask-p27/bin/activate" in .bashrc.
I'm not specifically all that familiar with Flask, but I suppose this may be python simply forking, running multiple threads to handle requests.
 
I did not see any attachment, BTW.
@mugojava, I've uploaded the file this time, sorry about the confusion.
Screen-Shot-2016-03-29-at-4.13.40-PM.png