Friday, September 17, 2010

HOWTO (Linux) - screen command to run long processes on background


Hi all,
When we need to run long processes on background and make sure the session remains, even if your desktop/laptop crash or is network disconnected. There is an alternative to VNC which is screen. This is very useful when to you have a long running process that you need to make sure does not fail due for external reasons.

Add this rc into your home (change screen –t lines as you wish)

[~]$ vi .screenrc
hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%= %{g}][%{B}%Y-%m-%d %{W}%c %{g}]'
# Default screens
screen -t SUP-app1 0 ssh -o ServerAliveInterval=60 user@host1
screen -t SUP-db1 1 ssh -o ServerAliveInterval=60 user@host2
screen -t SUP-db2 2 ssh -o ServerAliveInterval=60 user@host3

 

Run screen

[~]$ screen

Now you are in screen, your unix terminal is running in the server side.

To move from screen windows press (CRTL+a+” or CTRL+a+<screen number>), CRTL is a special key now, so please read the manual to avoid problems if you need to type CRTL+a for example. Press CRTL+a+? to display the help.

Make sure that you login to all your screen sessions, and also make sure ssh keep alive is set at client side in the server, otherwise you ssh session will timeout.

To check keep alive in the client see below. Remember this is not your local terminal is the ssh client in the server where screen is running.
 
$HOME/.ssh/config

 
and put:
 
ServerAliveInterval 60

or start screen with:

ssh -o ServerAliveInterval=60=yes
 
To detach from the screen session

CTRL+a+d

To re-attach
First, list the session available (as you can see I have 3 screen session, 1 already attached and 2 still running but detached)

[~]$ screen -ls
There are screens on:
        5050.pts-3.host1  (Attached)
        4214.pts-20.host2 (Detached)
        4919.pts-3.host3  (Detached)
3 Sockets in /var/run/screen/S-user.


Then, re-attach to the screen session selected.

[~]$ screen -r 4919.pts-3.host1



If session is already (Attached) then use -d to detach first and -r to re-attach


[~]$ screen -ls
There is a screen on:
        30392.pts-9.host1 (Attached)
1 Socket in /var/run/screen/S-user.

[~]$ screen -d -r 30392.pts-9.host1




Copy and Paste

C-a [ (copy) Enter copy/scrollback mode.
space (start select mode) press space and move up/down or pageup/down
space (end select mode) selection goes into the buffer
C-a ] (paste) Write the contents of the paste buffer to the stdin queue of the current window.

References:       
Thanks to my friend Neil for the tip. Enjoy it, it’s Linux….and it’s free.

No comments:

Post a Comment