What is a background process?
A background process is a process/command that is started from a terminal and runs in the background, without interaction from the user.
Some commands in Linux take time. In order not to waste our time when we have to use such commands, we can put them in the background of the terminal and continue our work. Most often this happens when we are hooked up to the terminal via SSH and we do not want to open ten more unnecessary windows.
In this article, we will talk about the background processes in Linux and we will show you how to start a command in the background and how to keep the process running after the shell session is closed.
What is the screen tool?
Linux Screen Command is a very useful command that offers the ability to use multiple shell windows (sessions) from a single SSH session. When the session is detached or there is a network disruption, the process that is started in a screen session will still run and you can re-attach to the screen session at any time.
How to install and run screen?
First we are going to install screen on our distribution.
# Install on Ubuntu \ Debian sudo apt-get install screen # Install on FreeBSD pkg install screen # Install on Arch Linux sudo pacman -S screen # Install on RHEL \ CentOS yum install screen # Install on Open Suse zypper install screenCode language: Bash (bash)
To use the command we need to write simply “screen“, and we have the opportunity to add a name of the process that will create a “screen -s name“
# Create a new instance screen -S testCode language: PHP (php)
You will have a new window like this one
Now you can execute the script or command or process that you need inside this window, for the example we are going to run the top command
# Run top command topCode language: PHP (php)
Now in order to leave top open in our screen and getting back to the terminal we have to press CTRL + A and after the letter D.
But wait how can we see the state of our test running screen with the top command? Easy just type screen -ls:
# Check current screen state screen -lsCode language: PHP (php)
You can see that we have a screen session named test, we are detached from the session but the process is still working.
To reattach to a screen, use the following command, substituting the number below with the process ID of your own. In this example the number is 65735
# Reattach to screen session screen -r 65735Code language: PHP (php)
To exit and destroy the session we can use the exit command inside the session.
If we want we can kill the process remotely using the id like in this example
# Kill process 65735 kill 65735Code language: PHP (php)
In conclusion, we can say that the “screen” command is easy to use and remember, it is valid in almost all distributions and most importantly it is reliable.