screen: Keep Your Processes Running Despite A Dropped Connection

I guess you all know this: you are connected to your server with SSH and in the middle of compiling some software or doing some other task which takes lots of time, and suddenly your connection drops for some reason, and you lose your work. This can be very annoying, but fortunately there is a small utility called screen which lets you reattach to a previous session so that you can finish your task. This short tutorial shows how to use screen for just this purpose.

Using screen

With screen you can create one or more sessions in your current SSH terminal. Just run screen
Code:
beacon% screen
to start it. This creates a screen session or window (although you don't see it as such) in your current SSH terminal:

Press Space or Return to get to the command prompt:

Looks like your normal SSH terminal, doesn't it?
Now I'm going to describe the most important screen commands that you need to control screen. These commands begin with CTRL a to distinguish them from normal shell commands.
• Ctrl a c - Creates a new screen session so that you can use more than one screen session at once.
• Ctrl a w - See how many screen windows do you have.
• Ctrl a a - Switches to the previous screen window(if you use more than one).
• Ctrl a n - Switches to the window number n+1 (next on the list). Where n is number of the current window.
• Ctrl a p - Switches to the window number n-1 (previous on the list). Where n is number of the current window.
• Ctrl a d - Detaches a screen session (without killing the processes in it - they continue).
• Ctrl a A - Give your window a unique name.

To close a screen session where all tasks are finished you can type:

Code:
beacon% exit

Now let's play around with it a little bit. In our screen window we run the command

Code:
beacon% top

Now let's create another screen session by typing
Code:
Ctrl a c

A new, blank screen session opens, and there we run ping command for e.g.
Code:
beacon% ping google.com


Now you can browse your two screen sessions by running
Ctrl a n, Ctrl a p , or the simplest way to switch between two recent used screen windows - Ctrl a a.
To see at which window you currently are issue Ctl a w command. The screen will output all the opened shell names in the bottom of the window. The current shell will be marked with asterisk(*).

Going further, let us give names to our windows. Type Ctl a A over the window you would like to rename. The screen will issue prompt "Set window's title to" in the bottom. Set the name you like. For example you can give name "ping" to the appropriate window.

Press Enter. The window is now given a unique name. Type Ctl a w to check that out.

To detach a screen session and return to your normal SSH terminal, type
Code:
Ctrl a d
Back on your normal SSH terminal, you can run
Code:
beacon% screen -ls
to get a list of your current screen sessions:

There is currently 1 screen session:

Code:
23746.pts-40.beacon     (Detached)

In case there is only one screen session you may reattach to it by issuing:

Code:
beacon% screen -r

Suppose, you want to bring up another screen session. All you have to do is to run again "screen" command on the normal ssh prompt.
Code:
beacon% screen
Now, if you detach all screen session and issue "screen -ls" again you will see there are 2 sessions now:
Code:
23746.pts-40.beacon     (Detached)
22140.pts-118.beacon    (Detached)

To reconnect to one of these sessions, run

Code:
beacon% screen -r 22140.pts-118.beacon

where 22140.pts-118.beacon is the name of one of the sessions from the screen -ls output.

My Connection Dropped - What Can I Do?

Now let's assume you edit source code in a screen session, something which normally takes a long time, and suddenly your connection drops. Thanks to screen your work isn't lost. Once your connection is back up, log in to your system with SSH again and run

Code:
beacon% screen -ls
as shown in earlier. From the results pick one session (e.g. 22140.pts-118.beacon) and reattach to it:

Code:
beacon% screen -r 22140.pts-118.beacon
If you picked the right session, you should find your code opened in the editor so that you can continue your work.
 
There is also tmux which is licensed under BSD license

it's pretty similar, many shortcuts are almost the same, only thing they start with ctrl+b instead of ctrl+a.
 
The Ubuntu folks created a nice screen-profiles package that makes screen much nicer to use, and makes it look more like tmux. Ars Technica has a nice overview. Shouldn't be too hard to extract the contents of the package to use the profiles on other OSes.
 
phoenix said:
The Ubuntu folks created a nice screen-profiles package that makes screen much nicer to use, and makes it look more like tmux. Ars Technica has a nice overview. Shouldn't be too hard to extract the contents of the package to use the profiles on other OSes.


I am wondering about getting these on FreeBSD as well. That would be very cool.
 
Thanks for those who mentioned tmux... I have a question, what TERM does tmux require as when I use vt100, I run tmux and it responds with:
open terminal failed: terminal does not support il1 or il

Looks like when I switched to xterm, it worked fine. I'm logging in using SecureCRT's ssh2 so it supports a lot of terminal types, what's the best terminal type and for the 256 color mode, when I start a tmux window, should the term type be screen?
 
killasmurf86 said:
Another reason to prefer tmux (at least for me) is that you can't create package for screen.

Yes, you can. The NO_PACKAGE recently got removed from the port.
 
Very helpful information.
However, I am having a bit of a issue and not sure what it is.

Downloaded and installed the port. Followed this tutorial. works well.

However, what is interesting is that I only see one screen session, even if I have two things running.

I followed the following example above, yet, when I do a screen -ls, I only see one session and it shows I am attached?

I can flip back and forth through using ctrl-a or ctrl-n/ctrl-p and see both my top and ping running, yet, when I detach, I only see one screen?

Am I doing something wrong?

I am ssh'ing from a Snow leopard box to a FreeBSD 8.0 server.

Any thoughts?

Thanks.

TCG
 
You did everything right - bug in tutorial

Hi thecoffeeguy,

You did everything right.
You just discovered a bug in tutorial. Thanks for being such an attentive person.

You see one session when doing screen -ls, cause when you follow the tutorial step by step you open only 1 session. It's no matter how many ssh sessions you open inside one screen session - still, you will see only one screen session when doing screen ls.

To open another screen session, you have to leave the current session (Ctrl a d) and just type screen again.

I will fix the tutorial, sorry for confusion.
 
bsdvm said:
Hi thecoffeeguy,

You did everything right.
You just discovered a bug in tutorial. Thanks for being such an attentive person.

You see one session when doing screen -ls, cause when you follow the tutorial step by step you open only 1 session. It's no matter how many ssh sessions you open inside one screen session - still, you will see only one screen session when doing screen ls.

To open another screen session, you have to leave the current session (Ctrl a d) and just type screen again.

I will fix the tutorial, sorry for confusion.

Ahh, ok. Sounds good. No problem.

I thought I figured it out when I was playing around. I thought, well maybe I need to detach my session. After doing that, and running screen -ls, then I saw multiple sessions.

Very good tutorial though. Always wanted to know how to run screen.

Thanks!

TCG
 
The screen-profiles package mentioned by phoenix can be found here:
https://launchpad.net/byobu

I noticed one thing tmux doesn't have that screen does, does tmux have anything equivelent to ctrl-A L in screen which basically toggles the pty as logged in or not so it shows up in w/who/finger. Seems that is a function missing in tmux.
 
Anyone here knows how to configure screen's .screenrc so it looks like tmux where the bottom of the screen looks like:

Code:
[0] 0:tcsh  1:alpine*  12:38 09-Feb-10

I could only get screen to show the shell but not the current process of that screen session like window 1 where it changes depending on the process and then when the session does a beep or something, it will highlight or reverse the colors of that session.
 
Here's the .screenrc that I use, to make screen behave like tmux (CTRL+B as the command-key, being the most important part):
Code:
# Fix the command key brokenness
escape ^Bb

# Remove the "hit enter" startup screen
startup_message off

# Add a status line at the bottom of the screen
caption always "%{Wb} %H %{Bk}| %{Ck}%-w%50>%{Cb} %n %t %{-}%+w%<%{- Wk}%{Bk} | %=%{Wb} %C "

# Set the size of the scrollback buffer
defscrollback 1000

# Automatically detach the running screen process on hangup (lost connection)
autodetach on
 
Thanks Phoenix, just tried it but 0 tcsh doesn't update with the name of the current process like it does in tmux. With tmux, if tcsh is the shell and I run something like vi, it would change to 0 vi.
 
Well, the functionality you want is a bit of a hassle in screen.
Basically, screen can read the commands you enter, and grab the input starting from the last character of your prompt.
I use bash myself, and the last character of the prompt is "$".

So, i would add the following to my .screenrc:
Code:
shelltitle " $ |bash"
If you become root however, the "$" becomes "#", so you're screwed again. So i changed the root prompt to "$" with a different color.

If you want a nice statusline here are two examples:
Code:
# status line
hardstatus on
hardstatus alwayslastline
#older simple hardline: hardstatus string "%w%=%m/%d %c"
hardstatus string '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}(%{W}%n*%f %t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%=$

I use screen all the time, but never heard of tmux. I'll probably be switching soon though now i know it exists.
 
I only used tmux because of this thread. I've used screen since 2003 but never really used a screenrc as I basically just use it on remote shell accounts elsewhere. I actually like screen more because tmux doesn't write to the utmp file so only the pty used for the actual login is shown and not the others like screen. The shelltitle " $ |bash" didn't really help as it just stays (0*$ bash) even when I su'ed to root. In tmux, the bash/tcsh doesn't change when you are root either but it just seems to change to the current running process since 0:tcsh would show but if I ran "ping www.yahoo.com" in the shell, the title changes to 0:ping so it seems to basically change to whatever is the current running process. Maybe it's a functionality that screen can't do for all I know.
 
There, i'm using tmux now.

To make life easier, i've added auto-reattach to my .bash_profile:
Code:
# If possible, reattach to an existing session
# If not possible, create a new session.

if [ ! $TMUX ]; then
tmux list-sessions > /dev/null
    if [ $? -ne 0 ]; then
        exec tmux new-session
    else
        exec tmux attach
    fi
fi

This is also possible for screen, add the following:
Code:
# If possible, reattach to an existing session
# and detach that session elsewhere. If not
# possible, create a new session.

      if [ -z "$STY" ]; then
          exec screen -dR
      fi
 
I know it's possible, but I can't for the life of me figure out how, to launch screen with one window in split region mode?

ie: I have screen set to open multiple windows on launch, but want window 0 to be split into two regions with an application running in each region
 
Here is the .screenrc I use. Hope it will help.
It is colorfull and outputs :
hostname | time | date | load | screen_number@$ screen_name
example :
myhost | 19:36 | 07.10.2010 | 0.00 0.00 0.03 | 0@$ pflog 1@$ bash 2@$ build 3@$ mail 4@$ jail

Code:
startup_message off 
#vbellwait 0.1
vbell_msg "*bell*"
# if activity is detected on an affected window switched into the background
# you  will  receive the activity notification message in the status line
defmonitor on
# change the way screen does highlighting for text marking and printing messages
sorendition "+b wr" # bold blanc sur rouge
# When  any activity occurs in a background window that is being monitored
# screen displays a notification in the message line
activity "activity -> %n%f %t" # window number , flags of the window , window title
# Defines the time message is displayed (default 5s)
msgwait 10
# hardstatus alwayslastline : screen reserve the lastline of the display for it
# %{b kw}%H    : hostname : bold white, black backgroung
# %{r}%1`      : backtick id 1 : red
# %{w}|        : | : white
# %{g}%c       : clock : green
# %{y}%d.%m.%Y : date : yellow
# %{g}%l       : load : green
# For the last argument list, actually I dont understand all this parameters but,
# it permit to list all window and display activity on them
# %{-b kw}%u %-Lw%{= rW}%50> %n%f %t %{-}%+Lw%<
hardstatus alwayslastline "%{b kw}%H %{r}%1` %{w}| %{g}%c %{w}| %{y}%d.%m.%Y %{w}| %{g}%l %{w}| %{-b kw}%u %-Lw%{= rW}%50> %n%f %t %{-}%+Lw%<"
# = copy mode options
defscrollback 10000

I know people minding Ctrl-a because of this hijacking the "go to beginning of input" in bash but you just can do Ctrl-a-a so…

(I really have to try that auto detach option, thanks phoenix).
 
Found a use for tmux. Scenario: ips monitor (excellent resolution once X is started) does not allow persistent resolution change before X is started, unless non-VGA input (s-video for example) is cabled, resulting in the lowest line off-screen (your prompt for example).
Solution: put tmux in .login or equivalent, its status line bumps the line one types on up one level, in this case, one's typing is visible again. (Until one figures out the proper data cable, if possible.) (I was planning to order the cable today, but in this case may put it off indefinitely, with such an easy workaround.)
..../edit/...
Just remembered, had to order the cable anyway, I was short either a VGA cable OR the s-video cable.
.../end edit/...
.../edit #2/...
tmux is now commented out, the data cable (s-video to s-video) works on the ips monitor... (I used tmux rather than dvtm because its manpage is much shorter! known because I have "lookat" set as $PAGER and it shows a status line of how many lines are in the manpage. If more freebsd users were used to this convenience, they I am sure would put lookat or a clone into $base... )
.../end edit #2/...
 
There's also a neat use for screen, other that helping not lose your running app when your ssh disconnects. Two users can connect to the same screen and then one to configure a server and the other to watch and learn configuration steps.

That way you can help your friends to learn how to configure/use a UNIX/Linux machine.
 
Back
Top