Use tmux to keep tasks running in the background after closing the SSH connection.

Victor Fernandez
2 min readApr 14, 2022

--

Photo by Mars on Unsplash

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:

  1. A Pi running a no desktop environment will be running a script.
  2. I need to be able to connect by SSH to this Pi and stop or start the script/software.
  3. I need the script/software to keep running in the Pi even if I close the SSH connection.

📒 What I need:

  1. Raspberry pi running Raspbian.
  2. Internet connection and SSH connection to the Pi
  3. Few minutes to kill.
  4. 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:

https://www.ocf.berkeley.edu/~ckuehl/tmux/

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.

Victor Fernandez

--

--

Victor Fernandez
Victor Fernandez

Written by Victor Fernandez

I’m Victor, I’m a Field Application Engineer for a CCTV manufacturer. I love Raspberry Pi, Python, and Microcontrollers and I write about my personal projects.

No responses yet