Many terminal programs are not intended to run as daemons, but despite this, they must run continually to operate. One example is Minecraft servers or migration jobs that take hours to complete.
In this short article, I will show a simple solution for continuing to run terminal programs even if you need to disconnect from the host or want to safeguard against SSH disconnection problems for critical operations on Debian-based Linux distros like Ubuntu and Linux Mint.
Setup
Installing screen
The only package needed for this functionality is "screen." This is preinstalled on many distros. To install it simply run
sudo apt install screen
Workflow overview
How to use screen
Once the screen package is installed, you can create a screen session that runs in the background and continues even if you disconnect from the host.
To use screen, the following workflow is used
- Create and attach a screen session.
- Start the process that needs to run in the background.
- Detach from the screen session.
- Do some other stuff, such as disconnect/connect from SSH, etc.
- Reattach to the screen session, check the status, or do more work in that session.
Create session
You can run multiple screen sessions. In this example, I will create a screen session that will be used to run console commands on a Minecraft server.
To start a screen session called minecraft, and attach to that session, run this command:
screen -S minecraft
Now, I can start the process I want to run. In this example, I want to enter the console of a Minecraft server I am running.
sudo -u minecraft msm haxorworld console
From this console, I can run commands that affect the game for my players. However, there is no way to disconnect from the Minecraft server console without stopping the Minecraft server. That's where the screen comes in and saves the day.
Detatching from session
To disconnect from a screen session, press "Ctrl+a" and "d" on your keyboard. This will take you back to your regular terminal session. Now, you can create more screen sessions or disconnect from the host and come back later.
Reattaching to a session
If you have multiple screen sessions running in the background, you can list them by running the following command:
screen -ls
There is a screen on:
889447.minecraft (08/31/2024 08:00:49 AM) (Detached)
1 Socket in /run/screen/S-stanley.
To reattach to the last used screen session, or run this command
screen -r
If you want to reattach to a specific screen session, in this example the session called "minecraft", run this command:
screen -r minecraft
Congratulations, you now have the power to run programs that are not intended to run as daemons, in the background, even when disconnecting from the host 🎉