Use tmux to keep tasks running in the background after closing the SSH connection.
The Problem:
Running scripts in a Raspberry pi (without a desktop environment) stops if I close the SSH connection.
The Solution:
Use the concept of screens to make the script or program run in the background.
The Implementation:
Install extra software to create detachable screens for the Raspberry pi.
These are not physical screens connected to the Pi. But rather terminal instances. So if I close the SSH connection, the software or script will still run in the background.
In other words:
- A Pi running a no desktop environment will be running a script.
- I need to be able to connect by SSH to this Pi and stop or start the script/software.
- I need the script/software to keep running in the Pi even if I close the SSH connection.
📒 What I need:
- Raspberry pi running Raspbian.
- Internet connection and SSH connection to the Pi
- Few minutes to kill.
- tmux (a terminal multiplexer)
What is tmux?
tmux
, as described in their GitHub, is:
A terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached.
Installation tmux
We are going to clone the repository from GitHub, so we use the following commands:
git clone <https://github.com/tmux/tmux.git>
cd tmux
sh autogen.sh
./configure && make
🔴 Solving "libevent not found" 🚨
I ran into an issue with some of the libraries. The error I got was libevent not found.
I found a solution on a StackOverflow post:
The command is here:
sudo apt install libavutil-dev tmux
Using tmux
To use tmux
, We need to type tmux
and a screen will be created.
We can run the program that we need or want on this screen, and before closing the SSH connection, we can use ctrl+b
later d
to detach the screen and leave it running in the background.
Here is a beginner’s guide:
Final Notes
- This problem is part of an educational exercise that I am running. Therefore I did not consider extra security measures. I will recommend consulting with a cybersecurity expert or IT professional to discuss if this type of connection follows proper security schemas.
tmux
is not the only option, but it was the option I feel more comfortable using, so I decided to use it in my exercise.