Using screen to detach long running process from current session

Sometimes we want to execute a program which is more heavy and time consuming or maybe to compile something which is again – time consuming. Starting such a process from our current session is not the best decision because we can’t terminate the session and have to wait the process to finish. Using SSH is even more risky because the SSH session may be interrupted and this will terminate our work. This is more painful if you have been waited for hours to execute a program and your SSH session goes down few minutes before you complete execution.

Here GNU Screen comes to help.

… is useful for dealing with multiple programs from a command line interface, and for separating programs from the session of the Unix shell that started the program, particularly so a remote process continues running even when the user is disconnected.

To install screen use your operating system package manager. In my case the following command do that:

sudo apt-get intall screen

Next step is to start screen. Just run screen from the termina:

screen

Now you’ve started a virtual console. You start your long running process here and instead waiting to complete, just detach the virtual terminal. To do that press CTRL + A and then D. This will detach the process and return you to your main session.
Now let’s list all detached screens:

scree -ls

The output should be similar to the following:

$ screen -ls
There is a screen on:
20855.pts-0.pi2 (02/11/2018 12:20:27 PM) (Detached)
1 Socket in /var/run/screen/S-pi.

To open again the detached screen run the following:

screen -r 20855.pts-0.pi2

Finally, but also important to know is how to close already started screen. To do that just type exit or press CTRL + D. This will terminate your current screen. I think that’s the most important you should know about screen. This tool is very handy and useful, so use it.

Leave a Reply

Your email address will not be published. Required fields are marked *