Keep processes running even if you close terminal / log out

You left the office in a hurry on Friday and forgot to run one process. Of course you can ssh to your desktop from home and put it running. But the problem is that the process takes several hours (or days) to complete. Do you need to keep you terminal and ssh connection open for all that time?

The answer is no. There are several ways of detaching a process from any display and thus killing the connection will not kill the process. The easiest method that I have encountered is screen. It is usually in the linux repositories, so for example in Ubuntu you can download it though apt. Note that you need to install it on the machine where want to run the executable.

Here's how it works.
1) Log in to the remote machine.
2) Run screen in command line. A new "virtual" shell will open (after you have pressed space or enter). The new shell is the one that will be detached.
3) Run your process.
4) Detach the display by pressing Ctrl+a and Ctrl+d in sequence. The original shell (where you typed screen) is displayed. You can now freely log out without affecting the detached process.
5) To resume to the virtual shell, log in again and run screen -r on the remote machine.
The detached shell is displayed again just as you left it. As if you had never logged out at all!
6) When you're finally done kill the virtual shell by running exit as usual.

screen has also other more advanced features. To be able to scroll the terminal press
Ctrl-a [ to enable copy mode. In this mode scrolling is possible with up/down keys.
Esc exits copy mode.

It is also possible to use command nohup for this task, but it's not as advanced as screen and it stores all output to logfiles.

Advertisements

4 Responses to “Keep processes running even if you close terminal / log out”

  1. Gustavo Serrano Says:

    Thanks, very useful.

  2. fumingsolder Says:

    I wish I knew about screen BEFORE I started this process that is running forever!
    Wouldn’t it be useful to have all processes run by default in a state that allows them to detach from terminal…

  3. forrarser ford Says:

    Man, that was absolutely fantastic piece of information that I needed, and quite on time. Many thanks !!!

  4. Al Says:

    Great, it works well.
    Thanks


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s