TweetFollow Us on Twitter

Screen: Living In A Virtual World

Volume Number: 21 (2005)
Issue Number: 9
Column Tag: Programming

Mac In The Shell

Screen: Living In A Virtual World

by Edward Marczak

Hello ladies and gentlemen! Step right up! Don't be afraid. Gather 'round! Come closer...that's it. Did you know that there are those who are hooked on the CLI? That some of us have to work on a monitor with less than 1024x768 of space? Or perhaps you know people that use ssh to perform a lot of work remotely? Today, I'll demonstrate the magic of "screen". For many, many reasons, screen is an indispensable utility. It's the answer - to several questions, for anyone doing command-line work, from the 12" iBook user, to the dual-G5 30" monitor owner. Watch, and be amazed!

The more things change...

My first job after graduation was at Computer Associates ("Hello, Doug!...who wouldn't know a Mac if he mistakenly walked into an Apple store!"). While CA has attempted to make a push into the PC world, in their heyday they had some of the best selling software for IBM "big iron" - mainframes. Of course, after thinking that I was going to get a job programming games or graphics (not that I had any real experience to speak of), this was an awakening into the things that companies really need. So, I sat down at my desk, and took a gander at the dumb-terminal green screen that was sitting on my desk, staring back at me. Good 'ol 5250 in all its glory. After a little introduction to the world of REXX, JCL and HLLAPI, I thought, "it would be great if I had another terminal here, so I could compare code on one screen without having to quit out and get back into what I'm working on." Well, Mr. Doug, who was a mainframe guy, showed me a great trick shortly after.

"Hey, Ed, I want to show you something really cool. Look at my terminal. Here, I'm logged into System B, but if I press Fn-F2, there's e-mail, and Fn-F3 brings up my text editor. And when I press Fn-F1, there's System B again! We use a system here called virtual terminals. Did anyone ever show you that?" Well, no, they hadn't. Now I had a way to be logged into several systems at once and not lose my place when I needed to switch to another. All with a single physical terminal sitting on my desk.

The more they stay the same!

What does this tale of mainframe tutelage have to do with modern day OS X? Well, virtual terminals, of course! Thanks to the hard work of the GNU volunteers that have contributed to "screen", we have fantastic virtual terminal facilities on our Macs (and Linux, and IRIX, etc.). So what, right? I can open up multiple terminal windows! This is 2005, buddy, and I'm not working on some crummy old green-screen. I've got a dual-mega-hyper-super-secret-quad-X-on-Intel-benchmark-smoking-egg-frying-electricity-sucking machine! I think 16GB of RAM can handle a terminal window or two!

Whoa! I'll show you why screen is more than just a way to have multiple terminals. Apple sees the light on this one, too: screen has shipped with OS X since 10.2. Thanks to this, we can even skip any discussion about acquiring the source or a package and getting it running on your system. We can get right to the good stuff!

What's that in the road? A Head?

What exactly is a virtual terminal? Instead of having physical screens attached to a system for each session, screen allows us to create a session that lives virtually. That is, not attached to any physical console. To even drive that point home, screen allows us to detach the session, and pick it up from anyplace else! Even better, you can have multiple people attached to a single session from anywhere, like a poor man's VNC.

Unix already supports job control. However, once you background a job and logout, you can't bring it back to the foreground. More than that, if you don't take special measures, a background job will die with the parent shell when you log out. No longer will you have to say, "I'm Mike Jones and I use nohup." (Especially if your name isn't Mike Jones).

For the impatient, pop open Terminal.app (or, the excellent iTerm, GLTerm, or other favorite), and type screen. You should get a simple welcome screen as shown here:

Screen version 4.00.02 (FAU) 5-Dec-03

Copyright (c) 1993-2002 Juergen Weigert, Michael Schroeder
Copyright (c) 1987 Oliver Laumann

This program is free software; you can redistribute it and/or modify it under the 
terms of the GNU General Public License as published by the Free Software Foundation; 
either version 2, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY 
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this 
program (see the file COPYING); if not, write to the Free Software Foundation, Inc., 
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

Send bugreports, fixes, enhancements, t-shirts, money, beer & pizza to screen@uni-erlangen.de


[Press Space or Return to end.]

Once you press space or return, you'll get back a prompt. That's it, you're running under screen! If you expected something fancier, sorry to disappoint, but you'll see that it's worth it!

^a (ctrl-a) becomes the important key when using screen. You use it to give screen commands. Now that you're in screen, here's a quick demonstration. Type ^a, followed by ":" (that's ^a, let go, type the colon). You will see the command mode prompt, ready for input - much like vi. Type "caption always" and press return. You'll see a status line along the bottom of your terminal. It should read, in reverse video, "0 bash". "0" is the window number and "bash" is the default window name. Let's give it something more descriptive. Type ^a-A, and you'll be prompted with:

Set window's title to: bash

Backspace over "bash" and fill in your own title for this window - I'm going to call mine "window0" - and press return. While you're there, get a file listing with ls -l, just to fill the window. Now for the magic: type ^a-c. This will create a new window. Your file listing will seem to disappear, and the status line will change to read "1 bash". This is simply a new terminal - all in the same terminal window. You can vaguely compare this to fast user switching without the cube effect, or switching users. window0 is still there, of course. Let's give this window a title right now. ^a-A, and I title mine window1. On this window, get a process listing with ps ax. Great. Now, how about another window? ^a-c, and you've got "2 bash". I'm going to title this one "topwin". Of course, then I'm going to run top:

top -ocpu.

It's great that we've created a few windows, but it's even more useful if we can move between them! There's a few ways to do that. Here's a quick list, followed by an explanation:

  • ^a-n - next window
  • a-p - previous window
  • ^a-# - Jump to window number "#"
  • ^a-^a - Jump to last window (like a 'back' button)

You can step through each window in order with ^a-n. Try it: you'll wrap to window0 and see the file listing that you left there. Press ^a-n again and you'll see window1 with its old process listing. One more time and you'll get our top display running on topwin (you left it running, didn't you?).

One more trick in the magic show. Press ^a-d. This will detach you from this session of screen. You'll be back to where you were before starting screen, with the exception of a note that says, "[detached]". Now log out. Yep, you heard me: Apple-Shift-Q and log out. This normally crushes all processes for your user. But screen will protect us here. Now, log back in. Open a terminal, and type screen -r. The -r flag instructs screen to "re-attach" to a detached screen, rather than start a new session. When you press return, you'll be magically transported right back to where you left off. Yeah, it's magic.

No! It's "What's that in the road ahead?"!

Anxious to learn more, are you? It would be difficult to present every single thing that screen can do in one column. Even two columns would be tough. So here are my favorite, practical tricks of screen, and how to perform them.

  • Multiplex Terminal.app - Ah, the wonders of modern technology! Look at this miniature marvel, the 12" PowerBook! Light and portable, it's everything you need in a traveling laptop. That is, of course, besides the screen real estate. One Terminal window looks great, but how many are you going to open? Just one, of course! Then run screen, and ^a-c to your heart's content. Even on a larger monitor, how many individual Terminal.app windows do you want?

  • Go home - Nothing like having a personal transporter to get you from place to place. Well, aside from the fact that they don't exist yet! But there is a way to end your workday on time and continue later on. I had a large copy job to run at the end of the day: over a Terabyte. But I was at the client's site, and not at home. Everyone else had gone for the day. Here's the trick: use a machine at the client's site that is accessible via ssh. Pop open Terminal.app and immediately run screen. You can then start your copy job, and disconnect using ^a-d, and go home. Once you're home (or wherever you're going), ssh in and run screen -r to reconnect and check on, or finish, the job. Why sit and stare at file copy status when you could be using that time to travel home?

  • Protect against an unexpected disconnect - In a world of broadband and high-speed access, there are still some secrets. The secret of the unreliable ISP is the most insidious. It's true! You may ssh into a remote machine over the Internet, only to find that you unceremoniously get dropped - Connection reset by peer, connection closed. Dial-up still exists, my friends! If you're managing via dialup, or find that you get dropped connections, run screen immediately after ssh-ing into a remote host. This way, if you get dropped while you're in the middle of editing an rc file with vi, you simply ssh back in, and type screen -r. You'll be right where you left off.

  • Have screen setup my environment for me - Amaze at the automatic setup! Swoon over the customized messages! screen looks for a .screenrc file in your home directory. You can customize the way screen starts up. Here's my startup file:

    defscrollback          20000
    activity 'Activity in local window %n'
    defmonitor                    on
    nethack                       on
    startup_message               off
    caption always "%{= g}%50-%t%{= g} %{= r}| %{= y}%c:%s %Y-%m-%d %{= r}| %{= g}%W"
    screen           -t           irc
    screen           -t           rootwin
    screen           -t           remotewin1
    screen           -t           remotewin2
    screen           -t           shamewin
    screen           -t           localwin
    screen           -t           sshtun

    Here's the explanations:


    defscrollback defines the scrollback buffer for each window.


    activity...defines the activity message. This goes hand-in-hand with the following line, defmonitor on. With this set, when a window you're not watching has activity in it - like when you're waiting for a compile to complete...or your irc session to show some activity - screen will display a status message to let you know. You can customize the message by following the directive with a string. "%n" will substitute the window number.


    nethack on is in my .screenrc file because, well, I'm a geek! With this option on, the standard screen messages are replaced with nethack-like ones. If you've just started using screen, this has the potential to confuse you. Otherwise, it's fun!...if you're me, I suppose.


    startup message off simply suppresses the intro screen.


    caption always, which we saw a simple example of earlier, can also accept a string that will define the status-line display.


    The final screen -t... lines simply fire up new windows for me, titled with the title I supply using the -t switch.


    There's much more about all of these features in the screen man page.


  • Screen sharing - There are many times that people call me for help, and solving the problem involves the command-line. Well, I really want them to watch what I'm doing so they can learn. For this exercise, I may be in place A, they're in place B and the server is in place C. Once again, I sprinkle a little magic dust over my keyboard and I can type in the same session as my remote friend! Of course, I'm just using screen's -x flag. Much like the -r switch, -x also re-connects to a session, although one that is not detached. It's called multi-display mode. Here's the easy way to use it. Have person A ssh into the server and start screen. Have person B ssh into the same server as the same user and run screen -x. Person A and person B will now be sharing the same session. Either user can type and both will see all screen output. What's nice about this is that if there are any sensitive passwords to type, and only one party knows them, you can let the prompt come up and let the appropriate person type it.

All good things...

Those 5 uses are the most common ways I use screen. Of course, there's plenty more in its top hat of tricks.

Since you can detach from a running session of screen, what happens if you start a new session of screen after detaching? Well, you'll have two separate sessions of screen running. If you detach from the second session, and try to reconnect, you'll realize that you have to tell screen which one to reconnect to:

$ screen -r
There are several suitable screens on:
        3848.ttyp1.Jack-Kerouak (Detached)
        574.ttyp2.Jack-Kerouak  (Detached)
Type "screen [-d] -r [pid.]tty.host" to resume one of them.

If I want to reconnect to the second session, I can tell screen that with the command screen -r 574. You can also find out this list anytime by using the -list flag:

$ screen -list
There are screens on:
        3848.ttyp1.Jack-Kerouak (Detached)
        574.ttyp2.Jack-Kerouak  (Detached)
2 Sockets in /tmp/uscreens/S-marczak.

Note that the sessions here are exclusive to a single user id. You won't pick up the detached sessions of other users. If something goes awry, and instead of "Detached" one session says "Dead", you can clear out it out with the "-wipe" flag: screen -wipe 3848.

screen will let you split your terminal. Create a few screens (^a-c), create some output on each, and then press ^a-S: Boom! Split-screen! ^a-Tab hops between segments. Each ^a-n (or -p, or -#) is independent of the other window. So, you could have top running in one split, with a long running app in the other. Of course, on my local Mac, I'd probably just open another terminal window, but this is pretty handy on a remote system. ^a-X removes the region that currently has the focus. This is why I never use Terminal.app's split bar. Thank you, screen!

You can screen into an app immediately by passing the program name into screen. screen vi somefile.txt will start vi under screen. This avoids spawning another copy of your shell, too. Naturally, all of the meta keys are then active, and you can create another window if you do need some other functionality.

screen can perform logging for you with the ^a-H keystroke combo. Again, this is of more use on a remote system that you may detach from, but want the output of some long running command. One pressed, ^a-H starts logging, tells you the name of the file it's logging into, and you're done. Pressed again turns off the log. Thought you'd like to know.

screen also sports a history buffer with copy and paste. Nethack mode gives some particularly good messages here. I'll be honest, this is a feature I barely use anymore locally. I have Terminal.app's unlimited scrollback buffer and a mouse. But remember, you can run screen and then disconnect. All of the output will accumulate in screen's scrollback, not on your terminal while in this state. ^a-[ gets you into copy/scrollback mode. Use the arrow keys to move around. Additionally, ^u and ^d will page up and down respectively. The escape key will bail you out.

There are plenty of other options and expansions on what is contained in this month's column. The man page happens to be excellent, so once you're comfortable with the basics, go dig in! One thing that is not possible as-is with the Apple-supplied screen is the ability to do anything fancy with multi-user. ACLs only work if the screen binary is set-uid. Naturally, any set-uid binary brings security implications, so I like the default of 'off' for this. If multiuser support with fine-grain ACLs is what you need, get out of screen, get root, and add the suid bit to screen: chmod 4755 /usr/bin/screen. Run screen again, and get a screen command line with ^a-: and type multiuser on. Then, grant another user full rights with acladd username. Then, "username" from the same system can access your session with "screen -x yourusername/". Otherwise, you can always set up a dummy account that both users can access, let on run screen first, and the second can connect with screen -x. Hit the man page for more information regarding ACLs.

Is there more wonderment? Isn't there always?!? While Apple does place the source to screen on the Darwin source site, there really isn't too much they had to change. The original source compiles cleanly and runs nicely. And just when I was about to say that there was a dearth of documentation regarding screen, I find these while Googling about: http://computing.ee.ethz.ch/sepp/screen-3.9 .9-to/ and http://rucus.ru.ac.za/docs/screen/. The former is a deeper look at most commands, while the latter is a really nice way to ease yourself into screen.

Must come to an end!

Is screen actually magic? I hope it feels like it to you. I think all technology seems like a small bit of reality (physics, electrical engineering, etc.) and magic. The people who created and continue to work on screen certainly have my humble thanks (plus, I sent them some Nastro Azzuro when I first found screen). The real magic of screen is certainly in the code itself; it allows me to be in more than one place at a time!

Next month, we'll get back to basics. bash basics: scripting for the admin.


Ed Marczak, owns and operates Radiotope, a technology consulting company that implements mail servers and mail automation. When not typing furiously, he spends time with his wife and two daughters. Get your mail on at http://www.radiotope.com

 
AAPL
$118.30
Apple Inc.
+1.83
MSFT
$47.80
Microsoft Corpora
-0.18
GOOG
$539.36
Google Inc.
+1.86

MacTech Search:
Community Search:

Software Updates via MacUpdate

ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more
SyncTwoFolders 2.0.6 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
Duplicate Annihilator 5.1.1 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more

Latest Forum Discussions

See All

The Sandbox EDU Review
The Sandbox EDU Review By Nadia Oxford on November 24th, 2014 Our Rating: :: COME PLAY IN THE SANDBOX AGAINUniversal App - Designed for iPhone and iPad Like its predecessor, The Sandbox EDU offers lots for players to see, do, and... | Read more »
Taichi Panda Hits iOS in December
Taichi Panda Hits iOS in December Posted by Jessica Fisher on November 24th, 2014 [ permalink ] Snail Games has released the first official game play trailer for  | Read more »
Skylanders, Show Off How You Fight Kaos...
Skylanders, Show Off How You Fight Kaos to Win Cool Prizes Posted by Jessica Fisher on November 24th, 2014 [ permalink ] iPad Only App - Designed for the iPad | Read more »
Playdek has Annouced a Delicious Thanksg...
Playdek has Annouced a Delicious Thanksgiving Sale Posted by Jessica Fisher on November 24th, 2014 [ permalink ] Playdek, makers of | Read more »
Pair Solitaire Review
Pair Solitaire Review By Jennifer Allen on November 24th, 2014 Our Rating: :: ADDICTIVE. SO ADDICTIVEUniversal App - Designed for iPhone and iPad Welcome to your new ‘five more minutes, oh no, why is it dark outside’ addiction.   | Read more »
DryGin Studios Release a Free-to-Play Ve...
DryGin Studios Release a Free-to-Play Version of Bio Inc Posted by Ellis Spice on November 24th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
The Hunted Review
The Hunted Review By Jordan Minor on November 24th, 2014 Our Rating: :: A GROAN IN THE DARKUniversal App - Designed for iPhone and iPad The Hunted’s multiplayer thrills are overshadowed by bland visuals and average gameplay.   | Read more »
Need for Speed No Limits has Been Unveil...
Need for Speed No Limits has Been Unveiled for iOS Posted by Ellis Spice on November 24th, 2014 [ permalink ] EA and Firemonkeys have announced Need for Speed No Limits, the next mobile installment | Read more »
Space Expedition Review
Space Expedition Review By Jordan Minor on November 24th, 2014 Our Rating: :: ONE SMALL STEPUniversal App - Designed for iPhone and iPad The only thing boring about Space Expedition’s lonely journey is its title.   | Read more »
Ubisoft Gives Everyone Two New Ways to E...
Ubisoft Gives Everyone Two New Ways to Earn In-Game Stuff for Far Cry 4 Posted by Jessica Fisher on November 21st, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Jumptuit Launches One-Tap Windows 8.1 iTunes...
Jumptuit has launched Windows 8.1 support for One-Tap iTunes Sync. with which Windows 8.1 users can now easily sync their iTunes libraries with Microsoft OneDrive. Jumptuit provides easy access from... Read more
CEA Study Finds More People Recycling Electro...
A new study by the Consumer Electronics Association (CEA) finds that electronics recycling receives the continued and growing support of consumers. According to the CEA,s Recycling and Reuse Study,... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1749. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of Parallels Desktop... Read more
27-inch 3.5GHz 5K iMac in stock today and on...
 B&H Photo has the new 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available... Read more
21-inch 1.4GHz iMac on sale for $979, save $1...
B&H Photo has the new 21″ 1.4GHz iMac on sale for $979.99 including free shipping plus NY sales tax only. Their price is $120 off MSRP. B&H will also include free copies of Parallels Desktop... Read more
13-inch 1.4GHz/256GB MacBook Air on sale for...
B&H Photo has lowered their price on the 13″ 1.4GHz/256GB MacBook Air to $1059.99 including free shipping plus NY sales tax only. Their price is $140 off MSRP, and it’s the lowest price for this... Read more
Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.