BigAdmin System Administration Portal
Feature Article
Print-friendly VersionPrint-friendly Version

Installing and Using GNU Screen

By Amy Rich

Much of today's system administration is done remotely by means of either a console server or a direct ssh connection to the machines themselves. Since these connections run over TCP, an unreliable IP network can cut the sysadmin's connection to a host during the middle of a critical task. Once that interactive session is disconnected, there's no way to return to the running processes, even if the shell continues to run on the remote machine. Screen, GNU's terminal-based windowing system, allows the sysadmin to reconnect to a running shell on a remote system so that poor network connectivity won't result in the loss of the session.

Screen is a full text-based windowing system designed to allow the multiplexing of several sessions in one physical window. All virtual windows are children of the initial screen process but run their programs completely independent of each other. Screen is generally run from an xterm or a directly attached serial terminal. A prefix key (C-a by default) combined with other keys allows the user to create new virtual windows, switch between virtual window, cut and paste using the cursor keys (even across virtual windows), scroll within the built-in history buffer, lock the terminal, and detach the screen session.

When starting a new session, screen first reads, in order, /usr/local/etc/screenrc, the file defined by $SCREENRC in a user's environment, and the user's $HOME/.screenrc. These files contain directives that customize screen on a per-user basis or globally if defined in /usr/local/etc/screenrc. After reading the resource files, screen creates a FIFO socket in the $SCREENDIR, often in /usr/tmp/screens/S-<username>. Unless otherwise specified, screen associates the socket with a session containing one virtual window running the user's shell or a specified command (such as emacs). One user may have multiple screen sessions running simultaneously if desired.

Once screen is run, any processes started from within the screen session stay active until explicitly ended or the screen session itself is ended or corrupted. If the user detaches from the screen session, a process listing will show the running processes, but the user is removed from wtmp and utmp so that utilities such as finger, who, and last do not show the user. When the user reconnects to the session, the utmp and wtmp information is modified and finger, who, and last once again list the user as logged in.

Building and Installing Screen

Screen is available from the Solaris Companion Software CD, ftp.uni-erlangen.de and various GNU mirror sites. To install it, download the source, unpack it, configure it, and compile it:

ncftpget ftp://ftp.uni-erlangen.de/pub/utilities/screen/screen-4.0.1.tar.gz
gtar zxf screen-4.0.1.tar.gz
cd screen-4.0.1
./configure
make
make install

This installs screen, but does not modify the termcap and terminfo databases or install the default screenrc file. To do so, copy ./terminfo/screencap and ./terminfo/screeninfo.src to /usr/local/etc and ./etc/etcscreenrc to /usr/local/etc/screenrc. Create the following files to prepare screen as a package for the Solaris OS:


screen-4.0.1-pkginfo

BASEDIR=/usr/local
PATH=/sbin:/usr/sbin:/usr/bin:/usr/sadm/install/bin
PKG=GNUscreen
NAME=screen
VERSION=4.0.1
ARCH=sun4u
CATEGORY=application
VENDOR=GNU
EMAIL=gnu@gnu.org
PSTAMP=20031015
CLASSES=none

screen-4.0.1-postinstall

#!/bin/sh

TERMCAPINFO=`/usr/bin/grep screen-w /etc/termcap`

if [ -r /etc/termcap ] && [ -f $BASEDIR/etc/screencap ] 
	&& [ "X$TERMCAPINFO" =  X]; then
  /bin/cp /etc/termcap /etc/termcap.orig
  /bin/cat $BASEDIR/etc/screencap >> /etc/termcap
fi

if [ -d /usr/share/lib/terminfo ]; then 
  /usr/bin/tic $BASEDIR/etc/screeninfo.src
  /usr/bin/chmod 644 /usr/share/lib/terminfo/s/screen*
fi

/bin/rm -f $BASEDIR/etc/screencap
/bin/rm -f $BASEDIR/etc/screeninfo.src

screen-4.0.1-prototype

i pkginfo=screen-4.0.1-pkginfo
i postinstall=screen-4.0.1-postinstall
!search /usr/local
d none bin 0755 root other
f none bin/screen-4.0.1 4755 root other
s none bin/screen=screen-4.0.1
d none etc 0755 root other
f none etc/screenrc 0644 root other
f none etc/screencap 0644 root other
f none etc/screeninfo.src 0644 root other
d none man 0755 root other
d none man/man1 0755 root other
f none man/man1/screen.1 0644 root other
d none info 0755 root other
f none info/screen.info 0644 root other
f none info/screen.info-1 0644 root other
f none info/screen.info-2 0644 root other
f none info/screen.info-3 0644 root other
f none info/screen.info-4 0644 root other
f none info/screen.info-5 0644 root other
f none info/dir 0644 root other

Run pkgmk to create the package, and then pkgtrans to translate the package into file format. Lastly, add the package, and screen should be ready to use.

/usr/bin/pkgmk -b /usr/local -o -f screen-4.0.1-prototype
cd /var/spool/pkg; /usr/bin/pkgtrans -s `pwd` /tmp/GNUscreen-4.0.1-sparc.pkg
rm -rf /var/spool/pkg/GNUscreen
/usr/bin/pkgadd -d /tmp/GNUscreen-4.0.1-sparc.pkg

Common Screen Tasks


Starting and Selecting Windows

Once screen is installed, it can be used without any further configuration. First run /usr/local/bin/screen to start a session. As mentioned previously, this starts one virtual shell window. Generally, additional shell windows are desirable and can be started with the prefix key followed by C-c, C-a C-c. This runs the screen command screen. Additional windows can also be run by entering screen's command mode and entering the command there. The command mode is entered by the key sequence C-a :. Once in command mode, type in screen and hit return. Every command that can be run by entering a key sequence can also be run by name from screen's command mode.

In addition to shell windows, screen can also attach directly to serial devices. This is quite useful when installed on a machine acting as a console server to a number of other machines or on a machine directly attached to a modem. To attach directly to /dev/ttyb, for example, enter command mode and give the screen command port as an argument: C-a : screen /dev/ttyb. This is shorthand for C-a : screen cu -l /dev/ttyb.

Once a screen session has multiple virtual windows, the user needs to easily switch between them. Like a TV remote, screen can access windows by using a wraparound previous/next mechanism or by specifying the window directly. Each window has an associated number, which gives it its place in the ring. To obtain information about all windows, enter the key sequence C-a . To obtain information about the current window, C-a i.

To switch to the next window in sequence, enter the key sequence C-a C-n, and to switch to the previous numbered window, C-a C-p. To hop directly to a window, enter the key sequence C-a # where # is the number of the window. For example, if there were a shell running in window 2, switch to it using C-a 2. To see a listing of all virtual windows and select one to switch to, enter C-a ". To hop back to the window last displayed, enter C-a C-a.


History, Cut and Paste, Logging, and Monitoring

When the user is working on a terminal that has no mouse, screen offers the capability to cut and paste by using a virtual clipboard. The key sequence C-a C-[ enters copy/history scrollback mode and allows the use of (mostly) vi-style syntax to navigate through the scrollback buffer. The motion options available in copy/history scrollback mode are covered in detail in the man page. The copy range is specified by setting two marks. The text between these marks will be highlighted and stored into the paste buffer. Press the space bar to set the first and second marks, respectively. To paste the text just saved to the buffer, go to the appropriate location in the desired window and enter the key sequence C-a C-].

Activity in a screen virtual window can be logged to a file, much like the UNIX script command does for an interactive session. To toggle logging of activity in the window to the file screenlog.#, where # is a number starting at 0, enter the key sequence C-a H. Along the same lines, a window can be watched for any activity. If the user is in window 3 and activity occurs in window 2, a message will be displayed at the bottom of the screen session if window 2 is being monitored. To toggle monitoring of the current window on the fly, use the key sequence C-a M.

Locking and Detaching, and Reattaching

Perhaps the two most useful features of screen are the ability to lock the terminal and the ability to disconnect the session and later reconnect. To lock the terminal (or xterm, if called from one), enter the key sequence C-a C-x. This runs /usr/bin/lock or an internal function and does not pass any input to the screen session from that terminal until the user's password is entered correctly. Processes in each window continue to run just as if the screen session were detached.

There are two ways to detach a screen session, power detach and a regular detach. In a regular detach (C-a C-d), the screen session is detached and the user is returned to the shell from which screen was invoked. In a power detach (C-a D D), the screen session is detached and the user is logged out of the calling shell. The user can also kill all windows and terminate screen instead of detaching by entering the key sequence C-a C-\.

Screen sessions can also be detached from outside the screen session, which is useful for stealing a session after changing physical locations. Again, sessions can be detached regularly or power detached, but if a user runs more than one screen session, the correct session to detach must first be determined. This is done by issuing screen -ls from the command line. On a machine called hostname where the user username is attached to two sessions, the output of the aforementioned command will look like:

% screen -ls
There are screens on:
        651.pts-5.hostname  (Attached)
        16405.pts-12.hostname       (Attached)
2 Sockets in /tmp/screens/S-username.

To detach the session 651.pts-5.hostname run one of the following commands, the first being a regular detach and the second being a power detach:

screen -d 651.pts-5.hostname
screen -D 651.pts-5.hostname

If there was only one active session, screen could be called without the session name:

screen -d 
screen -D

There are a variety of ways to reattach to a detached session, some of which will even detach the session first if needed. Each of the following is a command-line option to the screen program:

  • -r [pid.tty.host]: Reattach a detached session, optionally specifying which session.
  • -r sessionowner/[pid.tty.host]: Attach to another user's session running in multiuser mode. This argument requires that screen be installed SUID root and indicates that screen should look for sessions in another user's screen directory.
  • -R: Reattach to the first detached screen session found. If no detached session exists, this starts a new session using any additionally specified options. If a reattach is instead successful, all other command-line options are ignored.
  • -d -r: Reattach a session and if necessary detach it first.
  • -d -R: Reattach a session and if necessary detach or create it first.
  • -d -RR: Reattach a session and if necessary detach or create it first. Use the first session if more than one session is available.
  • -D -r: Reattach a session. If necessary power detach first.
  • -D -R: If a session is running, then reattach, power detaching first if necessary. If a session was not already running, create one and notify the user.
  • -D -RR: If the first session found is running, then reattach, power detaching the first if necessary. If a session was not already running, create one and notify the user.
  • -x: Attach to an already attached screen session. (Multi-display mode).

When a screen session dies, either because the machine rebooted or the process got killed or corrupted, the dead socket file can be left in the screen directory. A dead screen session cannot be reattached, and the sockets should be cleaned up. These dead screens are visible with the screen -ls command and can be cleaned out with the screen -wipe command.


Customizing Screen

Screen can be effectively run without any configuration at all, but most sysadmins will want to change some default behaviors and create shortcuts with key bindings. Most customization occurs via the screen resource files, though sessions can also be customized from the invoking command line or on the fly. Directives in the resource files set options, bind functions to keys, and automatically start virtual windows at the beginning of the session. Each directive is listed one per line with the arguments separated by tabs or spaces. The pound sign (#) acts as the comment delimiter, and any text appearing on a line after one is ignored. Any blank lines in the file are ignored. The arguments section of each directive can contain references to environment variables as well as plain text.

Here's a short example $HOME/.screenrc file containing comments for each directive:


# set some options
activity "activity: window ~%"  # Message when activity occurs in a window
vbell_msg "bell: window ~%"     # Message for visual bell
vbellwait 2                     # Seconds to pause the screen for visual bell
allpartial off                  # Refresh entire screen on window change
autodetach on                   # Autodetach session on hangup instead of
                                # terminating screen completely
bufferfile /tmp/screen-buffer   # Filename for the paste buffer
chdir                           # Change to the home directory
escape "``"                     # Redefine the prefix key to ` and define a
                                # literal ` as ``
shelltitle $HOST                # Set the title of all shell windows
defflow off                     # Set the default flow control mode
defmode 0620                    # Set the default mode of each pseudo tty
defscrollback 200               # Set the default number of scrollback lines
deflogin off                    # Do not register the window in utmp
startup_message off             # Disable startup messages


# virtual windows to start when screen starts
screen -t emacs@$HOST -h 0 1 /usr/local/bin/emacs -nw
                                # Start emacs in window 1 with a scrollback
                                # buffer of 0
screen -t tcsh@$HOST -ln -h 100 2
                                # Start a shell with the title of
                                # tcsh@.  turn off login mode
                                # (remove the window from utmp).  Use a
                                # scrollback of 100 lines and start the shell
                                # in window 2 (or the next available window)
monitor on                      # Monitor the above shell window

# keymap for use with the prefix key (backquote)
bind ' ' windows                # Show listing of all windows
bind 'a' prev                   # Previous window
bind 'c' copy                   # Copy paste buffer
bind 'e' screen -t emacs@$HOST -h 0 1 /usr/local/bin/emacs -nw
                                # Create new emacs window
bind 'i' info                   # Show info about the current window
bind 'n' next                   # Next window
bind 's' screen -t tcsh@$HOST -ln -h 100  # Create new shell window

As shown above, one very common modification is changing the prefix key from C-a (used in emacs to go to the beginning of the line) to something less frequently used. Picking an alternate prefix key can be difficult if the user makes full use of all of the keys; the alternate is usually a seldom-used combination involving the escape or control key. This makes for extra typing, of course, so one-key prefixes are optimal if the prefix key sees a lot of use.


Resources

The screen(1) man page contains a wealth of information for the power-user as well as the novice. It lists the defaults for the large number of customizable options, key bindings, and command-line arguments, as well as providing a few examples. Other resources include:

 


Unless otherwise licensed, code in all technical manuals herein (including articles, FAQs, samples) is provided under this License.


BigAdmin
  
 
 
 
Would you recommend this Sun site to a friend or colleague?
Contact About Sun News & Events Employment Site Map Privacy Terms of Use Trademarks Copyright Sun Microsystems, Inc.