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
$105.22
Apple Inc.
+0.39
MSFT
$46.13
Microsoft Corpora
+1.11
GOOG
$539.78
Google Inc.
-4.20

MacTech Search:
Community Search:

Software Updates via MacUpdate

OS X Server 4.0 - For OS X 10.10 Yosemit...
Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, develop software, host your own website, publish wikis, configure Mac, iPhone,... Read more
TotalFinder 1.6.12 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
BusyCal 2.6.3 - Powerful calendar app wi...
BusyCal is an award-winning desktop calendar that combines personal productivity features for individuals with powerful calendar sharing capabilities for families and workgroups. BusyCal's unique... Read more
calibre 2.7 - Complete e-library managem...
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
Skitch 2.7.3 - Take screenshots, annotat...
With Skitch, taking, annotating, and sharing screenshots or images is as fun as it is simple.Communicate and collaborate with images using Skitch and its intuitive, engaging drawing and annotating... Read more
Delicious Library 3.3.2 - Import, browse...
Delicious Library allows you to import, browse, and share all your books, movies, music, and video games with Delicious Library. Run your very own library from your home or office using our... Read more
Art Text 2.4.8 - Create high quality hea...
Art Text is an OS X application for creating high quality textual graphics, headings, logos, icons, Web site elements, and buttons. Thanks to multi-layer support, creating complex graphics is no... Read more
Live Interior 3D Pro 2.9.6 - Powerful an...
Live Interior 3D Pro is a powerful yet very intuitive interior designing application. View Video Tutorials It has every feature of Live Interior 3D Standard, plus some exclusive ones: Create multi... Read more
The Hit List 1.1.7 - Advanced reminder a...
The Hit List manages the daily chaos of your modern life. It's easy to learn - it's as easy as making lists. And it's powerful enough to let you plan, then forget, then act when the time is right.... Read more
jAlbum Pro 12.2.4 - Organize your digita...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more

Latest Forum Discussions

See All

Rami Ismail Opens Up distribute​() for D...
Rami Ismail Opens Up distribute​() for Developers Posted by Jessica Fisher on October 24th, 2014 [ permalink ] Rami Ismail, Chief Executive of Business and Development at indie game studio | Read more »
Great Hitman GO Goes on Sale and Gets Ne...
Great Hitman GO Goes on Sale and Gets New Update – Say That Three Times Fast Posted by Jessica Fisher on October 24th, 2014 [ permalink ] | Read more »
Rival Stars Basketball Review
Rival Stars Basketball Review By Jennifer Allen on October 24th, 2014 Our Rating: :: RESTRICTIVE BUT FUNUniversal App - Designed for iPhone and iPad Rival Stars Basketball is a fun mixture of basketball and card collecting but its... | Read more »
Rubicon Development Makes Over a Dozen o...
Rubicon Development Makes Over a Dozen of Their Games Free For This Weekend Only Posted by Jessica Fisher on October 24th, 2014 [ permalink ] | Read more »
I Am Dolphin Review
I Am Dolphin Review By Jennifer Allen on October 24th, 2014 Our Rating: :: NEARLY FIN-TASTICUniversal App - Designed for iPhone and iPad Swim around and eat nearly everything that moves in I Am Dolphin, a fun Ecco-ish kind of game... | Read more »
nPlayer looks to be the ultimate choice...
Developed by Newin Inc, nPlayer may seem like your standard video player – but is aiming to be the best in its field by providing high quality video play performance and support for a huge number of video formats and codecs. User reviews include... | Read more »
Fighting Fantasy: Caverns of the Snow Wi...
Fighting Fantasy: Caverns of the Snow Witch Review By Jennifer Allen on October 24th, 2014 Our Rating: :: CLASSY STORYTELLINGUniversal App - Designed for iPhone and iPad Fighting Fantasy: Caverns of the Snow Witch is a sterling... | Read more »
A Few Days Left (Games)
A Few Days Left 1.01 Device: iOS Universal Category: Games Price: $3.99, Version: 1.01 (iTunes) Description: Screenshots are in compliance to App Store's 4+ age rating! Please see App Preview for real game play! **Important: Make... | Read more »
Toca Boo (Education)
Toca Boo 1.0.2 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0.2 (iTunes) Description: BOO! Did I scare you!? My name is Bonnie and my family loves to spook! Do you want to scare them back? Follow me and I'll... | Read more »
Intuon (Games)
Intuon 1.1 Device: iOS Universal Category: Games Price: $.99, Version: 1.1 (iTunes) Description: Join the battle with your intuition in a new hardcore game Intuon! How well do you trust your intuition? Can you find a needle in a... | Read more »

Price Scanner via MacPrices.net

Weekend sale: 13-inch 128GB MacBook Air for $...
Best Buy has the 2014 13-inch 1.4GHz 128GB MacBook Air on sale for $849.99, or $150 off MSRP, on their online store. Choose free home shipping or free local store pickup (if available). Price valid... Read more
Nimbus Note Cross=Platform Notes Utility
Nimbus Note will make sure you never forget or lose your valuable data again. Create and edit notes, save web pages, screenshots and any other type of data – and share it all with your friends and... Read more
NewerTech’s Snuglet Makes MagSafe 2 Power Con...
NewerTech has introduced the Snuglet, a precision-manufactured ring designed to sit inside your MagSafe 2 connector port, providing a more snug fit to prevent your power cable from unintentional... Read more
Apple Planning To Sacrifice Gross Margins To...
Digitimes Research’s Jim Hsiao says its analysts believe Apple is planning to sacrifice its gross margins to save its tablet business, which has recently fallen into decline. They project that Apple’... Read more
Who’s On Now? – First Instant-Connect Search...
It’s nighttime and your car has broken down on the side of the highway. You need a tow truck right away, so you open an app on your iPhone, search for the closest tow truck and send an instant... Read more
13-inch 2.5GHz MacBook Pro on sale for $949,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $949.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $150 off MSRP. Price is... Read more
Save up to $125 on Retina MacBook Pros
B&H Photo has the new 2014 13″ and 15″ Retina MacBook Pros on sale for up to $125 off MSRP. Shipping is free, and B&H charges NY sales tax only. They’ll also include free copies of Parallels... Read more
Apple refurbished Time Capsules available sta...
The Apple Store has certified refurbished Time Capsules available for up to $60 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $255... Read more
Textilus New Word, Notes and PDF Processor fo...
Textilus is new word-crunching, notes, and PDF processor designed exclusively for the iPad. I haven’t had time to thoroughly check it out yet, but it looks great and early reviews are positive.... Read more
WD My Passport Pro Bus-Powered Thunderbolt RA...
WD’s My Passport Pro RAID solution is powered by an integrated Thunderbolt cable for true portability and speeds as high as 233 MB/s. HighlightsOverviewSpecifications Transfer, Back Up And Edit In... Read more

Jobs Board

*Apple* Solutions Consultant - Apple Inc. (U...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*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
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
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.