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.03
Apple Inc.
-0.16
MSFT
$44.40
Microsoft Corpora
-0.47
GOOG
$593.35
Google Inc.
-2.63

MacTech Search:
Community Search:

Software Updates via MacUpdate

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
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
Firefox 31.0 - Fast, safe Web browser. (...
Firefox for Mac offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals... Read more
Little Snitch 3.3.3 - Alerts you to outg...
Little Snitch gives you control over your private outgoing data. Track background activityAs soon as your computer connects to the Internet, applications often have permission to send any... Read more
Thunderbird 31.0 - Email client from Moz...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more
Together 3.2 - Store and organize all of...
Together helps you organize your Mac, giving you the ability to store, edit and preview your files in a single clean, uncluttered interface. Smart storage. With simple drag-and-drop functionality,... Read more
Cyberduck 4.5 - 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

Latest Forum Discussions

See All

LEX Goes Free For One Day In Honor of Ne...
LEX Goes Free For One Day In Honor of New Update Posted by Jennifer Allen on July 24th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Thomas Was Alone Goes Universal, Slashes...
Thomas Was Alone Goes Universal, Slashes Price to $3.99 Posted by Ellis Spice on July 24th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Meerkatz Challenge Review
Meerkatz Challenge Review By Jennifer Allen on July 24th, 2014 Our Rating: :: FONDLY PUZZLINGUniversal App - Designed for iPhone and iPad Cute and challenging, Meerkatz Challenge is a fun puzzle game, particularly for fans of... | Read more »
Book Your Appointment with F.E.A.R. this...
Book Your Appointment with F.E.A.R. | Read more »
It Came From Canada: Epic Skater
For all the hate that it gets for being a pastime for slackers, skateboarding really does require a lot of skill. All those flips and spins take real athleticism, and there’s all the jargon to memorize. Fortunately for us less extreme individuals,... | Read more »
Cultures Review
Cultures Review By Jennifer Allen on July 24th, 2014 Our Rating: :: SLOW-PACED EMPIRE BUILDINGiPad Only App - Designed for the iPad Cute it might seem, but Cultures is a bit too slow paced when it comes to those pesky timers to... | Read more »
More Paintings Have Been Added to Paint...
More Paintings Have Been Added to Paint it Back! Posted by Jessica Fisher on July 24th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
The Order of Souls Review
The Order of Souls Review By Campbell Bird on July 24th, 2014 Our Rating: :: STORY GRINDUniversal App - Designed for iPhone and iPad The Order of Souls is a free-to-play, turn-based RPG with a genre-mixing art style, interesting... | Read more »
Revolution 60 Review
Revolution 60 Review By Jordan Minor on July 24th, 2014 Our Rating: :: LASS EFFECTUniversal App - Designed for iPhone and iPad Revolution 60 is a bold, cinematic action game with ambition to spare.   | Read more »
Matter (Photography)
Matter 1.0.1 Device: iOS Universal Category: Photography Price: $1.99, Version: 1.0.1 (iTunes) Description: Add stunning 3D effects to your photos with real-time shadows and reflections. Export your creations as photos or video loops... | Read more »

Price Scanner via MacPrices.net

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
MacBook Airs on sale starting at $799, free s...
B&H Photo has the new 2014 MacBook Airs on sale for up to $100 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels... Read more
Apple 27″ Thunderbolt Display (refurbished) a...
The Apple Store has Apple Certified Refurbished 27″ Thunderbolt Displays available for $799 including free shipping. That’s $200 off the cost of new models. Read more
WaterField Designs Unveils Cycling Ride Pouch...
High end computer case and bag maker WaterField Designs of San Francisco now enters the cycling market with the introduction of the Cycling Ride Pouch – an upscale toolkit with a scratch-free iPhone... Read more
Kingston Digital Ships Large Capacity Near 1T...
Kingston Digital, Inc., the Flash memory affiliate of Kingston Technology Company, Inc.,has announced its latest addition to the SSDNow V300 series, the V310. The Kingston SSDNow V310 solid-state... Read more
Apple’s Fiscal Third Quarter Results; Record...
Apple has announced financial results for its fiscal 2014 third quarter ended June 28, 2014, racking up quarterly revenue of $37.4 billion and quarterly net profit of $7.7 billion, or $1.28 per... Read more
15-inch 2.0GHz MacBook Pro Retina on sale for...
B&H Photo has the 15″ 2.0GHz Retina MacBook Pro on sale for $1829 including free shipping plus NY sales tax only. Their price is $170 off MSRP. B&H will also include free copies of Parallels... Read more

Jobs Board

Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
Senior Interaction Designer, *Apple* Online...
**Job Summary** Apple is looking for a hands on Senior…will be a key player in designing for the Apple Online Store. The ideal designer will have a Read more
*Apple* Sales Chat Rep - Apple (United State...
…is looking for motivated, outgoing, and tech savvy individuals who want to offer Apple Customers an unparalleled customer experience over chat. At Apple , we believe Read more
Mac Expert - *Apple* Online Store Mexico -...
…MUST be fluent in English and Spanish to be considered for this position At Apple , we believe that hard work, a fun environment, creativity and innovation fuel the Read more
*Apple* Industrial Design CAD Sculptor - App...
**Job Summary** The Apple Industrial Design team is looking for a CAD sculptor/Digital 3D modeler to create high quality CAD models used in the industrial design process Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.