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
$97.67
Apple Inc.
+0.64
MSFT
$44.50
Microsoft Corpora
+0.10
GOOG
$589.02
Google Inc.
-4.33

MacTech Search:
Community Search:

Software Updates via MacUpdate

Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
TinkerTool 5.3 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Audio Hijack Pro 2.11.0 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Intermission 1.1.1 - Pause and rewind li...
Intermission allows you to pause and rewind live audio from any application on your Mac. Intermission will buffer up to 3 hours of audio, allowing users to skip through any assortment of audio... Read more
Autopano Giga 3.6 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
Airfoil 4.8.7 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
Microsoft Remote Desktop 8.0.8 - Connect...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
xACT 2.30 - Audio compression toolkit. (...
xACT stands for X Aaudio Compression Toolkit, an application that encodes and decodes FLAC, SHN, Monkey’s Audio, TTA, Wavpack, and Apple Lossless files. It also can encode these formats to MP3, AAC... Read more

Latest Forum Discussions

See All

This Week at 148Apps: July 21-25, 2014
Another Week of Expert App Reviews   At 148Apps, we help you sort through the great ocean of apps to find the ones we think you’ll like and the ones you’ll need. Our top picks become Editor’s Choice, our stamp of approval for apps with that little... | Read more »
Reddme for iPhone - The Reddit Client (...
Reddme for iPhone - The Reddit Client 1.0 Device: iOS iPhone Category: News Price: $.99, Version: 1.0 (iTunes) Description: Reddme for iPhone is an iOS 7-optimized Reddit client that offers a refreshing new way to experience Reddit... | Read more »
Jacob Jones and the Bigfoot Mystery : Ep...
Jacob Jones and the Bigfoot Mystery : Episode 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Jacob Jones is back in Episode 2 of one of Apples 'Best of 2013' games and an App Store... | Read more »
New Trailer For Outcast Odyssey, A New K...
New Trailer For Outcast Odyssey, A New Kind of Card Battler Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Out this Fall is a new kind of card battle game: Outcast Odyssey. | Read more »
Hay Day – Tip, Tricks, Strategies, and C...
Recently got into Supercell’s other huge hit, Hay Day and could do with some advice on what to do? We’ve got you covered with some helpful trips and tricks to bear in mind! Ticking Along One of the key things to keep in mind while building up that... | Read more »
Monster Head Review
Monster Head Review By Nadia Oxford on July 25th, 2014 Our Rating: :: FEEDING TIMEUniversal App - Designed for iPhone and iPad Racking up a high score with Monster Head is trickier than it first appears. The appeal wears out fairly... | Read more »
Garfield: Survival of the Fattest Coming...
Garfield: Survival of the Fattest Coming to iOS this Fall Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Who loves lasagna? Me. Also everyone’s favorite grumpy fat cat, Garfield. | Read more »
Happy Flock Review
Happy Flock Review By Andrew Fisher on July 25th, 2014 Our Rating: :: HERD IT ALL BEFOREUniversal App - Designed for iPhone and iPad Underneath the gloss of Happy Flock’s visuals is a game of very little substance. It’s cute, but... | Read more »
Square Register Updates Adds Offline Pay...
Square Register Updates Adds Offline Payments Posted by Ellis Spice on July 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Looking For Group – Hearthstone’s Curse...
For the first time since its release (which has thankfully been a much shorter window for iPad players than their PC counterparts), Blizzard’s wildly successful Hearthstone: Heroes of Warcraft CCG is sporting some brand new content: the single... | Read more »

Price Scanner via MacPrices.net

Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more
iMacs on sale for $150 off MSRP, $250 off for...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
Mac minis on sale for $100 off MSRP, starting...
Best Buy has Mac minis on sale for $100 off MSRP. Choose free shipping or free instant local store pickup. Prices are for online orders only, in-store prices may vary: 2.5GHz Mac mini: $499.99 2.3GHz... Read more
Global Tablet Market Grows 11% in Q2/14 Notwi...
Worldwide tablet sales grew 11.0 percent year over year in the second quarter of 2014, with shipments reaching 49.3 million units according to preliminary data from the International Data Corporation... Read more
New iPhone 6 Models to Have Staggered Release...
Digitimes’ Cage Chao and Steve Shen report that according to unnamed sources in Apple’s upstream iPhone supply chain, the new 5.5-inch iPhone will be released several months later than the new 4.7-... Read more
New iOS App Helps People Feel Good About thei...
Mobile shoppers looking for big savings at their favorite stores can turn to the Goodshop app, a new iOS app with the latest coupons and deals at more than 5,000 online stores. In addition to being a... Read more
Save on 5th generation refurbished iPod touch...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Many, but not all... Read more
What Should Apple’s Next MacBook Priority Be;...
Stabley Times’ Phil Moore says that after expanding its iMac lineup with a new low end model, Apple’s next Mac hardware decision will be how it wants to approach expanding its MacBook lineup as well... Read more
ArtRage For iPhone Painting App Free During C...
ArtRage for iPhone is currently being offered for free (regularly $1.99) during Comic-Con San Diego #SDCC, July 24-27, in celebration of the upcoming ArtRage 4.5 and other 64-bit versions of the... Read more
With The Apple/IBM Alliance, Is The iPad Now...
Almost since the iPad was rolled out in 2010, and especially after Apple made a 128 GB storage configuration available in 2012, there’s been debate over whether the iPad is a serious tool for... 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
WW Sales Program Manager, *Apple* Online St...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Lead Software Engineer, *Apple* Online Stor...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Manager, *Apple* Fullfillment Operation (AF...
…cross-functional teams to drive the highest level of program management quality for Apple . You will help plan launch strategy and demand generation programs with Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.