Power Sessions with Screen

Adam explains the many benefits and uses of screen.
Sessions

Now that you're creating new windows and bouncing around between them, you can get many things going in parallel. You could potentially have some editors, an IRC client and a few other things all running in their own windows. But occasionally disaster strikes, and your network connection dies (those of you still playing along at home can kill your SSH client). It looks like it's time to pick up the pieces and relaunch all of your applications on the remote machine, right? Not with screen.

Each time you start up screen without arguments, it creates a new session. This spawns two processes: a terminal management process and a client process. The client process automatically is “attached” to the terminal management process. When you type, the characters you enter go to the client, which sends them to the terminal management process, which then sends them to your application.

When your network connection dies, the client catches the signal and detaches from the terminal management process. The terminal management process continues along managing your terminals as if nothing happened. When you log back in, you can list running sessions by issuing screen -ls at the prompt. It should show something similar to the following:

There are screens on:
        24319.pts-9.hostname (Detached)
1 Sockets in /var/run/screen/S-youruserid.

This shows that your session automatically detached when your connection dropped.

You can re-attach to the session in a few ways. You can give a session name explicitly with screen -r sessionname. You can tell it to re-attach if possible, otherwise start a new session by running screen -R. Or you can go the “do whatever is needed to get a screen session” route and run screen -D -RR. This last option will detach already-attached clients and attach to the first session listed.

When you run one of these commands, you should be right where you left off before your network connection went down. When you're re-attached, you can continue working as if nothing ever happened.

It is also possible to attach to a session multiple times. This is useful if you haven't closed your screen session from another machine, or if you simply want to display windows from the same session side by side. You can multi-attach by adding an -x in the command-line options to screen when attaching.

Finally, when the end of the day rolls around and it's time to go home, you can detach from your session using Ctrl-A D. When you return the next day, you can re-attach, and you will be back where you left off.

Copy and Paste/Scrollback Mode

One of the key features listed in the beginning of the article was screen's searchable scrollback. This is a feature I could not live without. It's not immediately obvious to the new screen user, but screen's scrollback is accessed via the copy command. (You can enter copy mode with Ctrl-A [ or via the copy command.) Navigation works as expected with either the Arrow keys and Page Up/Down or the vi motion equivalents. Searching is accessed via either / and ? for vi-style search or Ctrl-S and Ctrl-R for incremental search. Case-insensitive search can be turned on with the screen command ignorecase yes. If you are using copy mode for scrollback only, it can be exited at any time with the Esc key.

To copy text, maneuver the cursor to the beginning of the desired text, and press the spacebar to mark it. Then position the cursor over the end of the text you'd like and press the spacebar again to mark it. When you mark the end, the text is copied into screen's internal copy buffer, and copy mode is exited. You can paste the text in your copy buffer into the active window with Ctrl-A ].

The final thing you should know about the copy and paste mode is the scrollback buffer is limited to 100 lines by default. This is, in my opinion, not enough. You can tweak this to a higher value (1,024 for example) by adding the command defscrollback 1024 to your .screenrc.

Opening Windows with screenrc

I have already mentioned that you can add a command to your .screenrc to change the behavior of screen. It's not immediately obvious, but you can put any screen command in a screenrc. This is very useful and can be used to spawn windows automatically with the screen command.

A typical application of this tidbit of knowledge is to launch a predefined set of windows at screen startup. Below is a sample screenrc that will do so:

# read in your normal screenrc
# before anything else
source $HOME/.screenrc
# now start opening windows
screen top
# it's possible to set the window title with
# the -t option
screen -t irc epic
# you can also specify the window number
# to launch in
screen -t mail 8 mutt
screen -t daemon 9 tail -f /var/log/daemon.log

If you save this to $HOME/.screenrc.multiwin you can tell screen to use it instead of your normal .screenrc by running screen -c $HOME/.screenrc.multiwin.

You also can launch more systems-oriented screen sessions from a startup script. A common application of a system screen session is a serial console server. Screen is well suited for this task because it has built-in support for serial terminals and logging. A commented example of a screenrc for this purpose is:

# This assumes that serialuser has proper
# permissions to access the serial ports and to
# write to the log files specified in the screenrc.
# turn logging on for all windows
deflog on
# tell screen to log to /var/log/serial.$WINDOW
logfile /var/log/serial.%n
# open windows on the serial ports
screen /dev/ttyS0 38400
screen /dev/ttyS1 19200

If you saved this file in /etc/screenrc.serial, you could launch it at startup with a script that runs:

su serialuser -c \
'screen -dmS serial -c /etc/screenrc.serial'
The -dmS serial options tell screen to launch the session in detached mode and name the session “serial”. User serialuser can log in and attach to this session exactly like any other normal screen session. Launching a detached screen also can be used to start screen from a cron job if this is preferred.

It is possible to set up a single system-wide screenrc that allows multiple users to connect to it. Screen supports multi-user mode with per-window ACLs that define what each user can and cannot do. Multi-user screen sessions, however, require that screen be setuid root. Because of this requirement, I am not going to include examples for multi-user screen sessions in an introductory article. If you would like to set up a multi-user screen session, read the screen docs, put on your “adding setuid root permissions to a complex piece of code” paranoia hat and be prepared to lock things down as tightly as possible.

As a third application, you could merge the two previous examples and launch system-wide interactive programs via screenrc. A good use of this would be launching mutella, a curses-based gnutella client, at startup. With screen, you can launch this program and connect to it on occasion to see the status, run queries, etc.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Re: Changing escape key sequence for screen.

Anonymous's picture

Far better is to use vi which doesn't require the use of control/meta keys!

Re: Changing escape key sequence for screen.

Anonymous's picture

C-g is also critical for canceling commands...

Re: Changing escape key sequence for screen.

Anonymous's picture

Alternatives include:

escape ^Oo (C-o opens a new line in emacs)
escape ^Pp (C-p moves the cursor to the previous line)

Re: Changing escape key sequence for screen.

Anonymous's picture

Five years ago my screen escape and literal command characters of choice for Emacs noninterference:

escape "^^^^"

Using Ctrl-^ was a bit awkward but I got used to it. If I were using screen as much nowadays I'd probably choose a different character, maybe even a function key.

The first thing I looked for

sqweek's picture

The first thing I looked for when I started using screen was an option to change the escape key - I didn't fancy having to hit C-a a to move to the start of the line.
After thinking about it for a while, I came up with this:
escape `\'
Which I'm a big fan of. For some reason hitting ` ' to get a backquote just feels intuitive (though it might help that I use dvorak so ' is where q is on qwerty).

Sessions for X

Anonymous's picture

I love screen. But what I want is something that can do stateful sessions with X programs when my X server crashes. VNC is to slow, and Xmove I couldn't get to work. Any suggestions?

My address is davidmccabe ta myrealbox tod com

if you'd like to contact me about that.

Thanks!

Re: Sessions for X

Anonymous's picture

have you looked at ratpoison? (http://ratpoison.sourceforge.net)

I thought I remember reading somewhere that you could detach and attach

sessions...but I can't seem to find it documented anywhere now. Anyway,

if you like screen, you might like ratpoison.

Re: Sessions for X

Anonymous's picture

Yes, I use Ratpoison right now, and no, it doesn't do that.

Re: Sessions for X

Anonymous's picture
Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix