# screen: Keep Your Processes Running Despite A Dropped Connection



## bsdvm (Apr 25, 2009)

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

```
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:


```
beacon% exit
```

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


```
beacon% top
```
 
Now let's create another screen session by typing

```
Ctrl a c
```

A new, blank screen session opens, and there we run ping command for e.g.

```
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

```
Ctrl a d
```
Back on your normal SSH terminal, you can run

```
beacon% screen -ls
```
to get a list of your current screen sessions:

There is currently 1 screen session:


```
23746.pts-40.beacon     (Detached)
```

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


```
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.

```
beacon% screen
```
Now, if you detach all screen session and issue "screen -ls" again you will see there are 2 sessions now:

```
23746.pts-40.beacon     (Detached)
22140.pts-118.beacon    (Detached)
```

To reconnect to one of these sessions, run


```
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


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


```
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.


----------



## graudeejs (Apr 25, 2009)

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.


----------



## phoenix (Apr 28, 2009)

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.


----------



## graudeejs (Apr 28, 2009)

once again i tried to use screen, but i'm so used to tmux.....
It feels so right


----------



## elchorizo (Apr 28, 2009)

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.


----------



## phospher (May 14, 2009)

screen... very nice. i'be been looking for something like this. thanks for the post.


----------



## gnemmi (May 15, 2009)

Thanks for teaching me how to use [cmd=]screen[/cmd]!
I'll be using it a lot =D

Best Regards


----------



## graudeejs (May 28, 2009)

Another reason to prefer tmux (at least for me) is that you can't create package for screen.


----------



## vincepoy (Feb 4, 2010)

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?


----------



## SirDice (Feb 4, 2010)

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.


----------



## thecoffeeguy (Feb 5, 2010)

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


----------



## bsdvm (Feb 6, 2010)

*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.


----------



## thecoffeeguy (Feb 8, 2010)

bsdvm said:
			
		

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



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


----------



## vincepoy (Feb 9, 2010)

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.


----------



## vincepoy (Feb 12, 2010)

Anyone here knows how to configure screen's .screenrc so it looks like tmux where the bottom of the screen looks like:


```
[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.


----------



## phoenix (Feb 13, 2010)

Here's the .screenrc that I use, to make screen behave like tmux (CTRL+B as the command-key, being the most important part):

```
# 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
```


----------



## vincepoy (Feb 13, 2010)

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.


----------



## p5ycho (Feb 18, 2010)

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:

```
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:

```
# 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.


----------



## vincepoy (Feb 22, 2010)

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 0ing 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.


----------



## p5ycho (Feb 23, 2010)

There, i'm using tmux now.

To make life easier, i've added auto-reattach to my .bash_profile:

```
# 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:

```
# 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
```


----------



## loop (Jun 3, 2010)

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


----------



## mecano (Oct 7, 2010)

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


```
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).


----------



## jb_fvwm2 (May 11, 2011)

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/...


----------



## mecano (May 11, 2011)

Key bindings! Use F1 and F2 to switch through screens, in .screenrc:


```
# F1    -> PREV
bindkey -k k1 prev
# F2    -> NEXT
bindkey -k k2 next
```


----------



## overmind (May 12, 2011)

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.


----------



## phoenix (May 12, 2011)

That's been possible on FreeBSD for a long time, using the snp(4) device and the watch(8) command.  You can even use it for a simple chat service.  It's something I miss on my non-FreeBSD boxes.


----------



## mecano (May 13, 2011)

watch(8)? Listen, that's a nice info, I never have been able to make that damn talk(1) to work.


----------



## _martin (May 13, 2011)

overmind said:
			
		

> 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.



You can use watch(8) for that too.

edit: ehm - I didn't see the @phoenix post above (probably was on last page or st.) - never mind then


----------



## _martin (May 14, 2011)

mecano said:
			
		

> watch(8)? Listen, that's a nice info, I never have been able to make that damn talk(1) to work.



First check whether both users have "mesg y" set. Next check if talkd is running. This was usually started by inetd and is commented out by default. 

`#  grep -vE '^$|^#' /etc/inetd.conf`


```
ntalk   dgram   udp     wait    tty:tty /usr/libexec/ntalkd     ntalkd
```
Don't forget to enable inetd in /etc/rc.conf and start it.
Then you can call somebody by (assuming localhost communication between 'steven' and 'fry'): 

`$ talk steven` and steven will respond with: `$ talk fry`


----------



## Alt (May 15, 2011)

I would ask someone to write a similar howto for tmux


----------



## mecano (May 16, 2011)

matoatlantis said:
			
		

> Don't forget to enable inetd in /etc/rc.conf and start it.



Oh, that must be why I didn't get any further with talk(1) - that, and now we are talking about it, also because I remember experimenting it under cousin OSX.


----------



## estrabd (May 20, 2011)

As a result of this thread, I switched from screen to tmux. It's much, much nicer.


----------



## mecano (May 21, 2011)

Could you please elaborate?


----------



## pmw (Jan 16, 2014)

*Re: screen: Keep Your Processes Running Despite A Dropped Co*

Hello,

Kind of an old thread but I can't get screen's hardstatus to work. It just doesn't appear. Same configuration on a Linux box is working fine. Last time I had the same kind of problems when I had my TERM configured the wrong way; but now, I'm using same TERM in FreeBSD as in Linux. I tried to google my problem but without success. I tried to make my hardstatus as simple as possible for testing purpose. Here's my .screenrc:

```
hardstatus on
hardstatus alwayslastline  "test"
```

`env`:


```
MM_CHARSET=UTF-8
SHELL=/bin/bash
TERM=xterm
CLICOLOR=YES
SSH_CLIENT=192.168.100.10 56630 22
SSH_TTY=/dev/pts/0
USER=user
TERMCAP=SC|screen|VT 100/ANSI X3.64 virtual terminal
LSCOLORS=ExGxFxdxCxDxDxhbadExEx
MAIL=/var/mail/user
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/sbin:/usr/local/bin:/home/user/bin
STY=60850.pts-0.kekkonen
BLOCKSIZE=K
PWD=/home/user
INPUTRC=/usr/local/etc/inputrc
EDITOR=/usr/local/bin/nano
LANG=fi_FI.UTF-8
PS1=\[\033[0;31m\]\u\[\033[0;32m\]@\[\033[0;31m\]\h\[\033[1;30m\]:\[\033[1;31m\]$(pwd)\[\033[1;30m\]$ \[\033[0m\]
HISTCONTROL=ignoredups
HOME=/home/user
SHLVL=2
LOGNAME=user
WINDOW=1
SSH_CONNECTION=192.168.100.100 56630 192.168.100.30 22
_=/usr/bin/env
```

Any suggestions?


----------

