Run A Program On Raspberry Pi After Closing SSH Connection
Are you one of those guys who prefer to use a headless Raspberry Pi connected via SSH?
Have you tried running a script on Raspberry Pi and wished you could terminate the SSH connection, shut down your PC and just go about doing your thing while the Pi keeps on running the script you asked it to?
There are multiple ways of keeping a program running in the background even after terminating the terminal process and/or the SSH connection.
The one that I particularly found apt for this situation is the ‘screen’. ‘Screen’ is not included in raspbian by default so we would have to install it on our Raspberry Pi.
Just in case you aren’t through the setup, here’s how: Setting up a Headless Raspberry Pi
Let’s start by SSH ‘ing into your Raspberry Pi:
[email protected]: ssh [email protected]
Once you have established a connection with your Raspberry Pi proceed further to,
1. Installing the ‘screen’ on your Pi:
[email protected]:~ $ sudo apt-get install screen
2. Check the number of ‘screen’ processes running by:
[email protected]:~ $ screen -list No sockets found in /var/run/screen/S-pi.
*This means that there are no current programs running using screen. Let’s start a process!
Say you want to run a python program called hey.py that prints out ‘HEY’ every 30 seconds.
#!/usr/bin/env pythons from time import sleep while True: print('HEY!') sleep(30)
3. Initiate a process on the ‘screen’:
[email protected]:~ $ screen python3 hey.py &
*The ‘&‘ keeps the process running in background
4. Break/Detach from the ‘screen’ process:
Press CRTL+A and CRTL+D in succession
5. Check for the ‘screen’ processes:
[email protected]:~ $ screen -list There is a screen on: 1840.pts-0.raspberrypi (15/02/18 12:13:31) (Detached) 1 Socket in /var/run/screen/S-pi.
*This shows that one screen process is running in the background. NOTE: In 1840.pts-0.raspberrypi
the 1840
is the process ID within ‘Screen’.
6. Re-enter the ‘screen’ process:
[email protected]:~ $ screen -r 1840
*If there is only one process running under screen then you don’t have to use the process ID.
You can view all the outputs in the particular ‘screen’ after re-entering it.
At this point you can exit the screen by pressing CRTL+A and CRTL+D
in succession. Exit the SSH connection and also the local terminal running on your PC, the program will keep on running unless you re-enter the screen and manually exit
the process.
Visit Screen on GNU.org
Check Out Other Beginner’s Articles on Learn2Create:
Guide to setting up a Raspberry Pi
Programming an Arduino using a Raspberry Pi
A beginner’s guide to Programming
A beginner’s guide to Android Development
A beginner’s guide to Robotics
Let us know of any updates or edits on this matter in the comment section below. Learn to create with Learn2Create!
A basic intro before I upload the net beans tutorial
https://www.facebook.com/mark.harrington.142892/videos/2039221846323827/