How to prevent a background process from being stopped after closing SSH client in Linux?

A background process in Linux is a process that is running independently of the shell. It provides us the privilege to leave the terminal window, and it will still be executing in the background without any interaction from the users.

Nginx and Apache web servers are the most common examples of the background processes that are used to serve images and dynamic content.

In Linux, we can start a process in the background by just appending the symbol after it.

Consider the example shown below −

sleep 10000 &

In the above command, we make use of the sleep statement that will run for a specified time that we just wrote after the statement and lastly followed by the & symbol to run the process in background.


immukul@192 ~ % sleep 10000 &
[1] 24101

Now the process is running in the background. We can also check the process with the help of the following command −



immukul@192 ~ % jobs

[1] running sleep 10000

Now we know what a background process is and how to run it, we can now focus on how to maintain the process state even after the ssh connection is closed.

The most widely used approach is to make use of the nohup command that Linux provides us with. It stands for “no hang up”, and its main purpose is to execute a command such that it ignores the hangup signal and therefore does not stop even when the ssh connection is down.

Just write the following command to the terminal and your process will not be killed even after the ssh connection is down −

nohup process_name &

There are certain cases where we would want to run the task on a low priority and in such cases we make use of the following command −

nohup nice process_name &

The nice command allows us to run processes on a lower priority.

Another way to achieve the same solution is to make use of the GNU Screen which can be found at this link. The GNU Screen allows us to disconnect from the server while all of our processes will continue to run in the background.

One more way is to establish a double fork, and the background process will not terminate, in that case run the following command to the terminal −

((mycommand &)&)