~s CWRU Unix Cookbook, at a glance CWRU Unix Cookbook, at a glance --------------------------------------------------------------------- Frank Wolff, scribe & editor, 406 Crawford Building, Thurs Jan 18, 1996 other contributers: Joan Carletta(xwd), Michael Somos(goodys), Leslie Picardo(newuser setup), Kevin Jacobs(security), Thom Gardner (general), Mike Knieser, Wei Zhao(vhdl,syntest,octtools) Reethi, Balan Ramasamy (vi), John Boes (gdb), Jackie Woldering (password). PLEASE contribute to or correct: wolff@alpha.ces.cwru.edu ---------------------------------------------------------------------- File location: /u/wolff/pub/unix.doc To print this document: nenscript -Phplj3 -2r /u/wolff/pub/unix.doc {machines: SPARC 4} enscript -Phplj3 -2r /u/wolff/pub/unix.doc {machines: SUN 3/60} or copy to your directory: cp -p /u/wolff/pub/unix.doc . ======================================================================== Newuser ------- 1. Get Unix account. Setup Unix account. Get freenet account. 2. Learn mail, elm and telnet. 3. Learn basic shell, file, directory and printer commands. 4. Learn an editor: ed, vi, emacs. 5. Learn x-windows: window manager, twm or fvwm. 6. Learn netscape: information highway. 7. Learn compilers: gcc and g++. 8. ...the rest of the manual. 1. Get Unix account. a) Go to a unix workstation. b) Type newuser after the "logon:" prompt ------- c) How to pick a password. Remember, the primary "defense" between your account and the world is your password! * Your password can be made up of upper and lower case letters A B C ... Z a b c ... z numbers 0 1 2 ... 9 other ./!@#$|%^&*()_-=+:"<>,./?~ * a mixture of upper and lower case letters, numbers, punctuation. * Make the password exactly 8 characters. Because Unix ignores after 8 and less than 8 is not a good password. * Do NOT use any common word from ANY language including slang or even proper names. Some BAD examples: dog, hotdog, smith, gopher * Adding before or after a common word does not help either! Some BAD examples: dog123, 123dog, 123dog456, .dog. * The best password is 8 completely random characters but this is hard to remember! * So use the first letter of each word in a sentence For example: "I have two cats and a black dog" Becomes: "Ih2c&abD" note: 2 for two, mixture of upper and lower, & for and. other nemonics are: 1 for one, * also to change your password use the command: yppasswd which asks for your old or new password. *** Warning -- The facilities manager is constantly running crack (i.e. to break your password). *** Warning -- It is a bad practice to give your password to others! New student help ---------------- A number of new students have come to me to help set up their accounts to use the X window system. Repeating this process n times is time consuming so I have created this write up to help you out. The following information should help you get started and avoid the frustation of having to figure out things like shells, window managers, startup scripts etc. Just follow these instructions and you should have a working account that will allow you to run X, open up remote terminal windows, emacs etc. { Leslie Picardo } ======================================================================== AA] login into your account ################## Setting up your unix shell ######################### A] First change your shell from the csh to tcsh. ( Why ? - because tcsh is better.) Do this > /bin/chsh Old shell: /bin/csh New shell: /bin/tcsh <---- type this in Password: <---- enter your password. NIS entry changed on omega You have now changed you shell to the 'tcsh' (T-shell). You will never have to repeat this again. B] You need a start up file called .tcshrc that the 'tcsh' shell uses to set the paths, prompt and create aliases etc. Do this > cd > cp /u/picardo/Begin/.tcshrc . C] Copy these files also. One is a login startup script and the other is a configuration script for the emacs editor. > cp /u/picardo/Begin/.login . > cp /u/picardo/Begin/.emacs . D] Now logout of the machine and login again for the 'tcsh' to take effect. ########### GET freenet account ######################################## d1] relogin after 10 minutes d2] type: telnet userid d3] login: getid d4] ...answer questions ########## Preparing your account to use the X window system ########### E] Create a directory called Util in your home directory and copy these useful shell scripts. 'rterm' helps you open up a remote xterminal window. 'remacs' helps you open a remote emacs window. Do this > cd > mkdir Util > cd Util > cp /u/picardo/Util/rterm . > cp /u/picardo/Util/remacs . F] Copy the following X window files into your directory. '.xinitrc' is a start up script read when the X window system begins '.twmrc' is a start up script for the 'twm' window manager program. '.Xdefaults' sets up default behavior for some X window programs. Do this > cd > cp /u/picardo/Begin/.xinitrc . > cp /u/picardo/Begin/.twmrc . > cp /u/picardo/Begin/.Xdefaults . G] To start the X window system on your machine type startx H] To use netscape, in the console window type: netscape& H] To log out of the X window system click on the middle button and select the "Exit TWM (only)" option. I] To log out of the machine type logout or cntrl-D ========================================================================= E-Mail ------ from Lists all the new letters in your mail frm Lists all the subject headers in your mailbox. whois -h whois To find the email, telephone of a person at CWRU For example: whois -h whois wolff mail reads your e-mail that you have recieved mail sub-commands - type mail return to read any mail ----------------------------------------------------- ? Lists all help commands h Lists the Headers & header number of a letters received. q Quit mail t # Type letter # s # file Save letter # into FILE z show next screen of email z- show previous screen of email r # reply to the letter # { saves from having to exit mail } A dot in column 1 terminates the letter. Control-C aborts it. man mail Gives all the MANual information on mail. To send mail ------------- To type a letter from the console and send it --------------------------------------------- mail help@alpha.ces.cwru.edu subject: Reminder to send new software { mail inserts the subject: } Dear Sir, Please send me the lastest software version. Thanks, Matthew . { period in column 1 and carrage } { ends the console input. } Important email addresses ------------------------- mail help@alpha.ces.cwru.edu This is the full IP address mail help This is the shorthand if connected to CES dept ---------------------------------------------- * help is for questions on hardware and software * A stupid question equals laziness meaning first check the unix man command or THIS documentation you are reading. mail broken Printer out of paper, software does not work mail postmaster Need help finding and ces email address. mail postmaster@po.cwru.edu for CWRU mail hostmaster@po.cwru.edu To get an IP address for your PC at CWRU mail grads Sends to all CES graduate students ---------------------------------- * USED by students and FOR students ONLY. Commonly students need to sell or buy stuff from each other. * All jobs, parties, GSS, GSA, or homework information is mailed here!!! mail gsa Send to CES Graduate Student Association faculty -------------------- mail beer Randy Beer mail carletta Joan Carletta mail ernst George Ernst mail ozsoy Meral Ozsoyoglu mail tekin Gultekin Ozsoyoglu mail andy Andy Podgurski mail cap Chris Papachristou mail saab Daniel Saab mail stephan Paul Stephan mail kumarv Kumar Vadaparty mail leew Lee White {Chairman} mail faculty Send to "ALL" CES faculty (rarely used). mail chandler Rose Chandler: Financal & Admin. Secretary mail nadine Nadine Hagoort: Executive & Chairman Secretary mail marla Marla Radvansky: CES Department Secretary mail staff Send to CES staff secretaries (rarely used). ~/.forward This is a special file which contains the forwarding email address if you wish your email sent elsewhere. Example: ed ~/.forward a wolff@alpha.ces.cwru.edu . wq finger This is used to check when a person has last logged on or "read" their mail. Example: finger wolff Sending mail via a file ----------------------- mail dest To find the email, telephone of a person at CWRU For example: whois -h whois wolff File Management --------------- ls LiSt current directory. ls -s List current directory showing filsize in kilobytes ls -l List current directory with user permission/time/date. ls *.c List all files in the current directory that end in dot c. ls ~/*.c List all *.c files in the user's home directory. ls -l cpu*.def List all files that start with cpu and end in dot def. ls -a List all hidden files (files that begin with a dot). ls -R LiSt current directory and all subdirectories. man ls Gives the all MANual information on the ls command. more hello.c Display the 'contents' of the file hello.c at 24 lines at a time. This prevents the text from scrolling by the screen. Press the space bar to proceed. Press q to quit. less hello.c A better version of more (quote: "less is more") zmore hello.c.Z Display compressed file zmore hello.c.gz Display a compressed "gzip" file man more Gives the all the MANual information on the more command. cp source dest CoPy a file from source to destination. Example, copy aaa.c to bbb.c: cp aaa.c bbb.c rm filename ReMove a filename from the current working directory. rm -v * ReMove files selectively (verbose) with y or n (yes/no). mv old new Rename (MoVe) the old filename with a new filename quota -v Display your disk space quota. du Display your "actual" disk usage (no holes counted!) holes: unix files sometimes contains holes holes are gaps in the file which represent zeros This is for efficient storage so that a file make appear to be 100 meg but actually be only 1K. du directory Display a directory usage df /tmp Display free space on temporary directory df ~ Display total free disk space where your account resides df Display all filesystems free space chmod a+x file CHange the access MODe for All users (User,Group,Others) to eXecutable. chmod g+rwx file CHange the access MODe for group to Read, Write, & eXecute. chmod u-rw file CHange to NOT allow user to read or write. chmod g=rx,o=rx directory Will make your directory public (g=r,o=r directory readonly will not do it) chmod -R g=,o= ~ CHange all files & subdirectories to private {See "Security" section in this document} PC DOS floppy file management (/usr/local/bin) ---------------------------------------------- mdir List the DOS directory on the floppy drive mcd Display the DOS current directory eject eject the floppy from the drive mread -t msdosfile . Read a DOS text file to current Unix directory mwrite -t unixfile . Write a Unix text file(\n) to DOS text format (\r\n) mread msdosfile . Read a DOS binary file to current unix directory mwrite unixfile . Write a Unix binary file to DOS floppy mtype msdosfile TYPE out a dos floppy file mdel msdosfile DELete a file on the DOS floppy mren oldname newname REName a DOS file from old to new mattrib [-a|+a] [-h|+h] [-r|+r] [-s|+s] msdosfile Change the file attribute mmd msdosdir Make a DOS Directory on the floppy mrd msdosdir Remove a DOS Directory on the floppy Useful Stuff ------------ cal 1995 displays the calendar for 1995 (man cal) dc Desk calculator (man dc) ls /u/ftp This is the CES ftp site where course information is held. ------------------------------ Hardware Software design tools ------------------------------ more /u/ftp/pub/ECMP317/HOW-TO-COMPASS vhdl, hardware design tool ghostview /u/ftp/pub/ECMP485/tutorial.ps octtools, compass, syntest ikos vhdl simulator PRINTING ----------------- lpr -P file PRint a file to a printer: Crawford building ----------------- "lpr -Palw2 file" for 2nd floor laser printer "lpr -Palw3 file" for 3nd floor laser printer "lpr file" for 3rd floor line printer lpq -P Line Print Queue Status: shows all the print jobs on the printer. "lpq -Palw2" for 2nd floor laser printer "lpq" for 3rd floor line printer lprm -P ReMove print job from Line Printer. ftp printservices To print to the HIGH SPEED LASER printer name: Give Freenet account NOT CES account password: cd crawford Print to 3rd floor Crawford room 314 -------------------------------------- {cd wade - wade commons building} {cd fribley - fribley commons building} put file quit telnet printservices login: status Will show print status of job cat -n file | lpr Add LINE NUMBERS to each line in an ascii text file. Also, "cat -n file | lpr -Palw2". enscript -Palw2 -2r file Print 2 pages per page (landscape: long way) in tiny letters. The ascii file is converted to postscript and printed to printer -Palw2 "enscript -Palw2 -2r -#3 file" will print 3 copies. {machines: SUN 3/60} nenscript -Palw2 -2r file same as above but for {machines: SPARC IPC} dvi2ps file.dvi | lpr -Palw2 Print a .dvi file which is generated by a TeX or LaTeX document compiler to printer -Palw2 dvi2tty file.dvi | lpr -Palw2 Print a .dvi file to an ascii line printer. Directory Management -------------------- pwd Display your Present Working Directory cd If lost then return to original login directory path mkdir xyz MaKe a DIRectory xyz. cd xyz Go down the directory to xyz (Change Directory). cd .. Go relative up the directory path. rmdir xyz ReMove "empty" DIRectory xyz. rmdir -R xyz ReMove NON-EMPTY directory cd /path Go absolute path addressing from the root directory. Administration -------------- uname -a Display Unix version: For example: SunOS zmo 4.1.4 2 sun4m ps -age Display all your process id's, time and command ps -agx Display all processes in the host machine kill -9 Kill a process displayed in "ps" nice Run a command at low priority vmstat -s Display virtual memory status vmstat -c cache flushing stats vmstat -f number of forks ypcat hosts | more Display host machines & ip their address of local domain ypcat -d ces.cwru.edu hosts | more Display hosts of a given domain ypcat hosts | grep Search for a host machine ip address ypcat passwd | more Display user password file of local domain ypcat -d ces.cwru.edu passwd | more Display hosts of a given domain ypcat passwd | grep Search for a given user ipcs -p ip status & of queues/semiphore/shared memory ipcrm -q remove message queue from ip ipcrm -m remove shared memory from ip ipcrm -s remove semiphore from ip netstat -r Display routing table of machine netstat -s Display tcp/ip packet statistics netstat -a Display tcp/ip socket statistics quota -v Display your disk space quota. du Display your "actual" disk usage (no holes counted!) du directory Display a directory usage df /tmp Display free space on temporary directory df ~ Display total free disk space where your account resides df Display all filesystems free space User Security measures on Unix ------------------------------ Unix file philosophy: It is "NOT illegal" for Unix users to probe as they please throughout the Unix file directories. If a directory is open then this tells the user (or process), it is okay to look in. ** Therefore, it is your responsiblity to protect your files. Summary ------- 1) Hidden files protected? ls -al chmod -R g=,o= ~ chmod o+x ~ chmod a+r ~/.plan ~/.project 2) Newly created files protected? umask 077 { everytime you login or place in init shell file } 3) Is your HOME directory protected? ls -dlL ~ Two solutions: a) mkdir ~/pub chmod u=rwx,g=rx,o=rx ~/pub mkdir ~/private chmod u=rwx,g=,o= ~/private ...move your private files into ~/private etc. b) ls -dlL ~ { -dlL ==> lowercase D, lowercase L, uppercase L } chmod u=rwx,g=,o= ~ 4) Has someone accessed my file? ls -lu or ls-lut 5) Encryption tools: netscape. 6) Work off floppies: mount, umount, mread, mwrite, mdir. Check for --------- 1) Hidden files protected? ----------------------- MYTH: "ls -l" displays all my files. A lot of people do "ls" or "ls -l" to list all files think it will list ALL files. THIS is a misconception: any file starting with a dot (i.e. ".") is considered a hidden file in Unix. "ls -a" or "ls -al" will show all hidden and visible files. If you do this you will observe a lot of hidden files which are typically NOT protected. These .files have information that you might find personal: .history { a history of the commands you typed } .cshrc { initial c shell file } .tcshrc { initial t shell file } .bashrc { initial bash shell file } .newsrc { news groups you read and which articles! } .netscape-history { where you have been on the net } { ..any special pictures downloaded!? } .netscape-bookmarks.html .mosaic-global-history Associated with each filename is read, write, execute bits for user, group, and others which are normally shown as: rwxrwxrwx uuugggooo When you do "ls -al" and you see the following for a particular file: rwxr--r-- filename This CLEARLY states that the file can be READ by user, group, and others BUT group and others cannot WRITE or EXECUTE from it. MYTH: "chmod g=,o= *" will protected all files. NO, only visiable ones AND only in the current directory (i.e. no subdirectories) How to protect files: chmod -R g=,o= ~ chmod o+x ~ chmod a+r ~/.plan ~/.project This will protect files read, write, execute from group and others. And the -R option will process all subdirectories! Depending on how many subdirectories you have, this may be a slow command. 2) Newly created files protected? umask set up correctly? ------------------------------------------------------ It very common for people not to set up their initial shell file up properly. The "umask" shell command tells the type of security you have enabled. The umask command set the protect bits for your files when "YOU" create them either by shells, editors, mail, netscape, mosaic, and other tools. * For example, EMACS while you are editing a file will create an autosave file in your directory which has the form: #filename# in your directory. If you do not have the umask set properly, others (i.e. everyone) can read it your #filename# even though you filename is protected! * A lot of programs use temporary files (i.e. /tmp directory ) in which files are left behind with lots of personal stuff via aborts, crashes, etc. Shell command format: umask UGO * Sets the DEFAULT mask protect bits any time file is created on the unix system. U is user rwx (i.e. yourself), G is group rwx, O is others rwx. Where rwx is read, write and execute protect bits in "octal". * If umask is typed by itself (i.e. no arguments) then is will display your current mask. Example: umask if the display is the typical 22 or 022 then 0 2 2 in octal 000 010 010 in binary rwx rWx rWx UUU GGG GGG which means that you are masking group and others from writing BUT everyone can still READ your file! Thus the DEFAULT for unix shells is to allow others to read from your files. How to protect created files: 1) edit your shell file: .cshrc .tcshrc .bashrc 2) add at the top line: umask 077 this will block group and others. 3) Is your HOME directory protected? ------------------------------------- Your HOME directory is the directory: a) whenever you login b) cd { with no arguments } c) cd ~ { i.e. tilde ~ means home directory } To see the protection of your home directory: ls -dlL ~ { -dlL ~ ==> lowercase D, lowercase L, uppercase L, blank, tilde } it probably is shows rwxr--r-- which means others can read it. There are 2 solutions: a) Create 2 directories in you home directory: mkdir ~/pub chmod u=rwx,g=rx,o=rx ~/pub mkdir ~/private chmod u=rwx,g=,o= This allows you to place public document for others to access in your ~/pub. And ~/private you can place all your personal stuff. Optionally you can modify your .tcshrc file to have at the last line "cd ~/private" so that when you login it will place you by default to your private directory/ b) Drastic Second solution: completely protect your home directory!! chmod -R g=,o= ~ 4) Has someone access my file? --------------------------- The unix file maintains for each file: last modified time last accessed time ls -l By default, when you list the directory, it shows the last time the file was modified (i.e. written too). ls -lt This sorts the files by last modified time instead of alphabetic ls -lu This lists the file by last accessed time (i.e. read or written to). ls -lu filename This is for a particular file. ls -lut This sorts the files by last accessed. So by looking at the access time, and compare it with modified time or whenever you last remembered looking at it; you can tell if someone has accessed it. This is a selfcheck to see if someone has "graded" your project. 5) File Encryption offers more security. ------------------------------------- Unix file protection is good but not the best. People can break into the system even get the supervisor login. Or tape backups can be stolen (hey, didn't think of that one!) IRS Corporate law, as least where I worked, required software vaults (i.e. secure & fireproof) for tape backups. Or people can listen on the net, since most people are working off the "file server". If you have a local disk on your workstation then place your private stuff there. << part #2>>> Netscape offers a way to create a Secure Area or Zone which will do the encryption automatically. --This one is not free. 5) Finally, even encryption can fail, so work off a floppy disk directly: mount, umount, mdir, mread, mwrite. And when done at the end of the day, umount it and remove the floppy. (or saver yet, seperate pc not connected to the net) ------- Editors ------- ed - classic unix line editor (must learn for unix career!) vi - classic unix screen editor emacs - screen editor - for those who don't care for unix. ed - UNIX line Editor --------------------- For remote processing this is a must because in screen mode processing like Emacs, noise on the phone line sneaks in characters which one does not know about. One can use screen editors but at a painful risk. Editing a New File ------------------ ed EDiting a brand new file. a Append new text abcdef enter text 'abcdef' then return key (or enter). 111111 enter another line of text . a dot in the first column means end of input w newfilename Write the new filename out q Quit the unix editor & enter the Unix command mode. Editing an Old File ------------------- ed oldfilename EDit an old (existing) text file. Editor Commands --------------- Text input ---------- a Append text AFTER the current text line. To end the input text mode, type a period in column one & return. i Insert text BEFORE the current text line. To end the input text mode: type a period in column one & return. Line addressing --------------- go down to the next line & make it current. - go up one line & print it. -5 go up relative five lines and print. +2 go down relative 2 lines and print it. . print the current line .+10 go to ten lines from 10 go to ABSOLUTE line 10 (tenth line from top of file). $ go to the LAST line in the file. Printing & finding text ----------------------- 1,20p Print lines 1 to 20 on the screen. 1,$p Print lines 1 to the end of the file on the screen. .,.+20p Print 20 lines from the current line. .=p Print the current line number & Print it. g/xyz/.=p Print all line numbers & text which contain the string xyz. Deleting text ------------- dp Delete the current line & Print it. 15,23dp Delete lines 15 through 23. Substituting Text ----------------- s/old/new/p Substitute the string 'old' with 'new' in the current line & Print the substituted line. 2,10s/old/new/gp Global Substitute all strings 'old' with 'new' between lines 2 through 10 & Print them. Using Unix Shell commands inside the editor ------------------------------------------- !ls List files in the current directory. !pwd Present Working Directory. !rm file ReMove a file !cp src dest CoPy a file from Source to destination. !command Any Unix command. --------- vi editor --------- This is the traditional screen unix editor. If you intend to be a unix user this is a must to learn and use. vilearn This program will teach you the vi editor vi filename if the file exists, it will be opened if the file does NOT exist, then a NEW file will be created vi consists of three modes: navigate mode: move around the file insert mode: insert text into the file command mode: execute shell commands and ed commands Text input ---------- a Append text AFTER the current text line. To end the input text mode: press ESC key. i Insert text BEFORE the current text line. To end the input text mode: press ESC key. line addressing after you start vi by DEFAULT you are in navigate mode --------------- l --> Character Forward: move cursor right one char. w Word forward: move cursor to next word h <-- Character Backward: move cursor left one char. b Word backword: move cursor to last word x Character delete 0 Point to beginning of the line. $ Point to end of the line. k Previous line j Next line down Ctrl-b Back full page Ctrl-f Forward full page Ctrl-d Back half page (down) Ctrl-u Forward half page (up) :.= Print current line number. #G Goto line number where # is line number 1G Goto first line in the file 25G Goto 25th line in the file G Goto last line in the file /pattern Search for a "pattern" n Find next pattern Command mode (each command ends with a "return" or "enter" key) ------------ :w Save a file, and return key but do not exit vi. :w filename Save under a different filename :r filename Include a file in your current file. :wq Write file and Quit vi. :x eXit: same as :wq :q! Quit vi and DO NOT save the file Printing & finding text ----------------------- :set nu Set line numbering on :1,20p Print lines 1 to 20 on the screen. :1,$p Print lines 1 to the end of the file on the screen. :.,.+20p Print 20 lines from the current line & move to last line :.=p Print the current line number & Print it. :g/xyz/.=p Print all line numbers & text which contain the string xyz. Deleting text ------------- dd Delete the current line 2dd Delete 2 lines 3dd Delete 3 lines dw Delete the current word J Join two lines: delete carriage return from current line u Undo last command (limited to only the last operation) :dp Delete the current line & Print it. :15,23dp Delete lines 15 through 23. Copying text ------------ yy Copy current line into clipboard 2yy Copy 2 lines p paste clipboard into text (anytime) Substituting Text ----------------- :s/old/new/p Substitute the string 'old' with 'new' in the current line & Print the substituted line. :2,10s/old/new/gp Global Substitute all strings 'old' with 'new' between lines 2 through 10 & Print them. Using Unix Shell commands inside the editor ------------------------------------------- :!ls List files in the current directory. :!pwd Present Working Directory. :!rm file ReMove a file :!cp src dest CoPy a file from Source to destination. :!command Any Unix command. -------------------------------------- Emacs at a Glance - full screen editor -------------------------------------- This is a full screen editor which is used under UNIX or Xwindows compared to a line editor (ed) which only uses a line at a time. (For remote users type: setenv TERM vt100) Note 1: Ctrl-f (1 press) means press the control key simultaneously with the lower case f key. Esc v (2 press) means first press the escape key and then the the lower case v key. Note 2: )]} When ever a left paraenthesis is typed, the cursor will temporarily jump to the corresponding right paraenthesis, to show the user the matched set. Ctrl-g Abort current command, use this whenever you are lost. It will not exit from the editor or hurt anything. This will be one of your most important commands. Ctrl-f --> Character Forward: move cursor right one char. Ctrl-b <-- Character Backward: move cursor left one char. Ctrl-d Character delete Ctrl-a Point to beginning of the line. Ctrl-e Point to end of the line. Ctrl-p Previous line up Ctrl-n Next line down Esc v Back page Ctrl-v Next page Ctrl-x = Print current line number. Ctrl-x g Goto line number: Ctrl-x Ctrl-s Save a file, type name if new, else just return key. Ctrl-x Ctrl-f Find (load) a file, type filename after Ctrl-f. Ctrl-x i Include a file in your current file. Ctrl-x Ctrl-c Exit EMACS. EMACS will ask if you need a file to be saved. Ctrl-space Mark a position in the file. Copying Text Step ------------ ---- Ctrl-space 1) START: Mark the starting point of what you want to move. 2) END: Then move your cursor to the END of what you are moving. Ctrl-w Ctrl-y 3) This will copy the marked text into a paste buffer. 4) Now move your cursor to your destination. Ctrl-y 5) COPY: This will YANK your text into current cursor position. Moving Text Step ------------ ---- Ctrl-space 1) START: Mark the starting point of what you want to move. 2) END: Then move your cursor to the END of what you are moving. Ctrl-w 3) This will move the marked text into a paste buffer. 4) Now move your cursor to your destination. Ctrl-y 5) MOVE: This will YANK your text into current cursor position. Deleting Text Step ------------- ---- Ctrl-space 1) START: Mark the starting point of what you want to move. 2) END: Then move your cursor to the END of what you are moving. Ctrl-w 3) DELETE: This will delete the marked text, and maintain a copy of it in the paste buffer. Searching Text Step -------------- ---- Ctrl-s 1) This will start the search. 2) As you type each character on the string you are searching for, Emacs will move the cursor to the new position. 3) If you made a mistake just backspace or Ctrl-g to abort and start over. Ctrl-s 4) If this string is not the one you are interested in and want to find another one just like it, then type Ctrl-s as many times to find the next instance. Ctrl-r 5) (Optional) if you accidentally missed the string and want to reverse and look at the previous string match then type Ctrl-r as many times as you like. Esc 6) If this is were you want to stop, then press the Escape key. Ctrl-g 7) If you have not found what you are interested in and want to return to your orignal position, type Ctrl-g to abort the search. Esc x overwrite-mode This turns off the auto-insert mode which is good for drawing stick pictures. For Sun WorkStations - the following useful keys are predefined --------------------------------------------------------------- R7 R8 R9 previous screen page up one line next screen page <-- R10 R11 R12 --> left one character set mark right one character R13 R14 R15 top of file down one line goto end of file F4 ... F7 save a file read a file L8: display all files beginning edited. Move cursor via up/down arrows and hit the space bar to select an already loaded file. -------------- Network/system -------------- finger Displays the last logon of user for a particular machine, last time mail is read, and the ~/username/.plan file (if it exists). Example: finger wolff@ces.cwru.edu **** finger has been modified at the CES and is non-standard. "finger username" is not the same as "finger username@server" For example, "finger wolff@easy" will only show the last time "wolff" logged on at "easy" and also show the ".plan" file. "finger wolff@bravo" will show ALL machines that "wolff" is logged on to and the TRUE last logon time but it will NOT show the ".plan" file. finger @ Will finger all the users on the host machine For example: finger @emerald.ces.cwru.edu ypcat hosts | more Will display all the host machines in your domain rusers Lists all the users on the system rusers Lists all the users on a machine name: easy, fox, ... who Lists all users on the current machine logged in arch Displays the architecture of the current host: sun4 mach Displays the processor type of the current host: SPARC hostname Displays the current hostname (machine): guardian hostid Display the current host internet hexidecimal address domainname Displasy the domain of the current host: ces.cwru.edu netstat -r Display routing table of machine netstat -s Display tcp/ip packet statistics netstat -a Display tcp/ip socket statistics ypcat -x Displays the current domain, map nickname table (i.e. hosts, services, group, passwd) ypcat hosts | more Display the host machines & their ip address ypcat hosts | grep Display ip address for a given host ping Display if a machine is "dead" or "alive" (/usr/etc) ----------------------------------------- Example: ping guardian Example: ping guardian.ces.cwru.edu yppasswd Change your password for the current domain ypcat services Display the network services & port numbers For example: smtp 25/tcp mail ypcat passwd Display the network password/shell file ypcat group Display the access group codes more /etc/hosts Lists all the machine file server names more /etc/hosts.equiv Lists all machine names more /etc/aliases Lists all CES dept. email addresses rup | more List hosts (machines) up time ruptime | more rsh remote shell command executes a "single" shell command on the remote machine, returns back to your local machine and also, sends standard out and error to your local machine. rsh guardian ls list the directory on the guardian machine rcp remote copy: copy files from the remote machine to the local and vise versa. Read: man rsh rlogin remote login to another machine. Don't forget to check the "setenv" for the proper terminal type. Example: rlogin guardian.ces.cwru.edu X-window rlogin --------------- Suppose you are currently logon to machine "easy" and want to rlogon to machine "monroe" and execute a remote X-window program: "xdvi sample". (1) xhost monroe (2) rlogin monroe (3) setenv DISPLAY easy:0 (5) xdvi sample setenv Display all your user environment variables (bash use "export" instead of "setenv") setenv Example: "setenv TERM vt100" will set the variable TERM to vt100. This happens to be a vt100 terminal type. (bash shell: export TERM=vt100) stty -a Display all the terminal(tty) characteristics Talking Live, person to person around the world ----------------------------------------------- talk (1) Type "setenv" and check if TERM is vt100 If not then type, "setenv TERM vt100" (2) The remote person must be logged-on Type "finger " to find out. where " where dest is the internet email address. (4) The remote user sees a message on the console. Then the remote user types, "talk " (5) If every is ok, then a split screen will appear and just start typing away. The lower screen in from the remote talker. (6) Type control-C to terminate the talk. write is a another way to talk but it forces you to have to write the email address each time. Of course, this used if talk is not working or just want to send a message. This requires the remote user to be logged on. Remote Dial-in to Case Western Reserve University ------------------------------------------------- See cwru web site also: http://www.cwru.edu ------------------------------------------------- 1200 baud, No Parity, 8 bits, 2 Stop bits. vt100 need this terminal type if using EMACS or VI editor. 368-8888 Phone number to get in login: Enter your "freenet" logon name WHICH is diferent than your Unix account. password: Enter your "freenet" password note: to get a "freenet" account under your unix account just type: telnet freenet-a from your unix account. connect machine For machine names see below. rlogin machine Remote login to a machine from another unix machine. Everyone should NOT login to the same machine, for this will overload that machine. If your response time is slow, re-login to another machine. Do not worry, all your files will still be there because they are on a shared disk. Another machine does not mean another disk system. All machines in the same type have a shared disk. ypcat hosts | more List hosts & their ip addresses in your domain ---------------------------------------------- more /etc/aliases if no ypcat: Lists all CES dept. email addresses more /etc/hosts Lists all the machine file server names more /etc/hosts.equiv Lists all machine names Here are some examples: Machine Type Physical Location -------- -------- ----------------- easy Sun 3/60 2nd floor Crawford Building fox Sun 3/60 2nd floor Crawford Building harry Sun 3/60 2nd floor Crawford Building john Sun 3/60 2nd floor Crawford Building king Sun 3/60 2nd floor Crawford Building lenny Sun 3/60 2nd floor Crawford Building delta Sun 3/60 2nd floor Crawford Building george Sun 3/60 2nd floor Crawford Building lpr -Palw2 Apple LaserWriter 2nd floor Crawford Building beryl SPARC IPC 3rd floor Room 320 Crawford diamond SPARC IPC 3rd floor Room 320 Crawford cerberos SPARC IPC 3rd floor Room 320 Crawford guardian SPARC IPC 3rd floor Room 320 Crawford chitra SUN 3/60 3rd floor Room 320 Crawford sandy SUN 3/60 3rd floor Room 320 Crawford picasso SUN 3/60 3rd floor Room 320 Crawford monroe SUN 3/60 3rd floor Room 320 Crawford lpr -Palw3 Apple LaserWriter 3nd floor Crawford Building papaya SUN 3/50 3rd floor Room 304 Crawford emerald SPARC IPC 3rd floor Room 304 Crawford flourite SPARC IPC 3rd floor Room 304 Crawford lychee SUN 3/50 3rd floor Room 304 Crawford lpr line printer 3rd floor Room 304 Crawford 1987: SUN 3/50 16 Mhz 68000, SUN 3/60 20 Mhz 68000 1992: SPARC IPC 25 Mhz MIPS? 2nd floor Crawford: Black & White workstation room 320 Crawford: Color Workstation room. logon: .... enter your Unix (not freenet) login. password:... enter your Unix (not freenet) password. setenv Displays your current ENVironment (bash shell: export) setenv TERM vt100 Tells unix your remote terminal type if using Emacs editor. (bash shell: export TERM=vt100) Ctrl-d Whenever you are in trouble, press the Control key and the 'd' together. This will terminate any running program. logout To exit from unix. ftp This is for remote File Transfer Program between CWRU machines. Once inside ftp, ------------------------------------------------------ ? for help. ls -l to list the remote directory. delete file DELETES the remote file pwd shows the remote present working directory. cd path to change the remote directory path. To send a file: first 'open remote_machine_name', then 'send file1', ..., 'send fileN', and then type 'quit'. To receive a file: first 'open remote_machine_name', then 'recv file1', ..., 'recv fileN', and then type 'quit'. All machines in the Smith Lab have ftp including the PC's which is useful when transfering to foppy. SLIP accounts ------------- If you have a Personal Computer and wish to have internet directly connected to your machine, the university will provide you a slip account. You will first need a "freenet" account which is DIFFERENT from a CES account. telenet userid First get a freenet account from CWRU login: getid This may take a week!? telnet getslip To get a internet SLIP account login: getslip When the login prompt shows type: getslip CWRUnet ID: Give your freenet login NOT your CES account. This also will take a week!? Large scale file management commands (Finding text & files when you forget) --------------------------------------------------------------------------- tar cvf Tape ARchiver: copy all files/directories into a tarfile Example: "tar cvf zzz.tar *" creates a tar file called "zzz.tar" and then copies all files "*" into it. tar xvf e(x)tract all files from the tarfile. (gzip have superceded the old unix compress programs) ---------------------------------------------------- gzip file Compress a "file" into "file.gz" gunzip file.gz Decompress a "file.gz" into "file" (gzip -d file.gz) unzip file.zip Decompress a pkunzip archive file. This format is usually used on Personal Computers. gzcat file.Z gzcat file.gz Read a "gzip" compressed file zmore file.Z Same as "zcat file.Z | more" zmore file.gz gzcat file.tar.Z | tar tf - | more Display compressed tar file table of contents (i.e. list files inside compressed tar file) This avoids decompressing on disk and running out of disk space. gzcat file.tar.Z | tar xvf - E(x)tract all files from a compress tar file compress Compress a file or tarfile in order to save space. Example: "compress zzz.tar" will compress zzz.tar and rename it as "zzz.tar.Z". Example: "compress *" compress all files and append ".Z" to each file. uncompress file.Z Uncompress the file. mkdir zzz { Make a new directory } cp filename.tar.Z zzz/. { Copy the filename.tar.Z into the directory } cd zzz { Change to the new directory } uncompress * { Uncompress this file, the ".Z" is removed } tar xvf * { Extract from the archived file } zcat file.Z Read a compressed file to standard out zcat file.Z | more ..and pipe to more. zcat file.tar.Z | tar tf - | more Display compressed tar file table of contents (i.e. list files inside compressed tar file) This avoids decompressing on disk and running out of disk space. zcat file.tar.Z | tar xvf - E(x)tract all files from a compress tar file pack file Huffman file compression (note: lower case .z) unpack file.z ..This is rarely used. Searching file contents: grep, egrep, fgrep and zgrep ----------------------------------------------------- egrep "include" *.c Show the lines of all files (which end in dot c) which contain the string include. egrep "(fopen|include)" *.c *.h Show the lines of all files (*.c & *.h only) which contain the string, fopen, or include. find . -name "xyz*" Search current directory and all sub-directories for any filenames which begin with xyz. Languages --------- cc sourcefilename.c Will compile a "sourcefilename.c" language program and place it in the executable file "a.out". To execute, just type "a.out". The "man cc" will give further information. ==> USE GCC please! cc source.c -o source.exe Will compile a "C" language program and place it in the executable file "source.exe". To execute, just type "source.exe". rehash This makes the shell aware of a new executable program. cc src.c -lX11 -o src.exe Will compile a "src.c" C language program using the Xwindows object library (X11) and place it in the executable file "src.exe". gcc -pg src.c This is the perferred compiler. Is the ANSI C language compiler using all the same options of the "cc" compiler. The "man gcc" will give further information. Option[-p]: output "gprof" profile information Option[-g]: output "gdb" debugging information Set your path to: /usr/local/bin cflow *.c Display function call table "Which calls which" similar to a xref. lint *.c C program verifier across several programs ***Do use at ces dept. *** to old cxref *.c C symbolic cross reference program Where each variable or function is defined/used. ***Do use at ces dept. *** to old gdb a.out This is the symbolic debugger. (/usr/local/bin) gprof >stats Write profiling information to file "stats" (/usr/ucb) indent src.c out.c Pretty print file "src.c" to file "out.c" (/usr/bin) g++ C++ compiler: for object-orientated programming. (/usr/local/bin) ar Library archiver: maintain object *.o libraries. Creates sequential library (/usr/5bin, /usr/bin) ranlib Builds index header in front of library archive for random access. (i.e. must do for using libs) nm file.o Print symbol names contained in the object file.o Also, "nm a.out" for gcc default executable ld file1.o file2.o link editor: combines object files and libraries to create an executable. (called by gcc internally) make Makefile: maintain source file (single version). rcs Revision Control System: maintain multiple source files. (GNU). lex Compiler tool: construct regular expressions. (/usr/bin) flex Compiler tool: Gnu version of lex (faster). (/usr/local/bin) yacc Compiler tool: construct context free grammars. (/usr/bin) byacc Compiler tool: Berkely yacc version (best). (/usr/local/bin) bison Compiler tool: Gnu version of yacc. (/usr/local/bin) gcl LISP interpreter (GNU lisp) sp Prolog interpreter. Set your path to: /usr/lang/prolog/bin latex sample.tex Will compile a latex document "sample.tex" into a "sample.dvi" file. "xdvi sample.dvi" will display the latex file in graphics mode under X-windows. Set your path to: /usr/local/bin dvi2ps sample.dvi > sample.ps Convert a .dvi file into a postscript file (.ps). dvi2ps sample.dvi | lpr -Palw2 Print a .dvi file on a postscript printer. dvi2tty sample.dvi > ascii.txt Will convert a .dvi file into an ascii text file. Of course, any graphics will not be translated but it is useful for printing documents to a ascii line printer (draft) or converting to another word processor or view on a dumb ascii terminal. awk Pattern matching program gawk GNU version of awk sh Execute a shell command or script file script file is the name for a batch file. Utilities --------- gzip GNU (MIT developed) compression/decompression program (ftp site: prep.ai.mit.edu directory: /pub/gnu) compress Standard unix compression program uncompress Standard unix de-compression program My first C program ------------------ Use the Editor to enter the following program ed hello.c Start editor a editor command to add text, add until a dot in column 1 main() { printf("hello world\n"); } . end of input, dot in column 1 and return w editor command to write text to file xyz.c q editor command to quit editor and return to Unix gcc hello.c compile C program rehash This makes the shell aware of a new executable program. a.out execute C program Program should print, hello world to display! How do I make my C program look nice? ------------------------------------- man indent This displays all the options to indent. indent in.c out.c This will read the C source program file in.c and fix up the indenting and write it to out.c gdb a at Glance --------------- This is the symbolic debugger for the gcc compiler. Symbolic means that the source code is recoginized by the debugger. So keep all your source files and executables in the same current working directory. gcc -g hello.c Compile the C program xyz.c and put the executable in a.out The -g flag is only needed by gdb. gdb a.out Start the debugger and read the a.out file. h gdb Help command: lists all the command groups. i fu Lists all your functions that you used in your program. l Lists the source code of the function. b This sets a Breakpoint in your program. b main Set your first Breakpoint to the function main. info breakpoints Display all the breakpoints r Start Running your program and stop at any breakpoints. n Single step a single source line but do NOT enter the subroutine. s Single step a single source line but enter the subroutine disp DISPlay the contents of a variable in your program. und UN-Display a debugging variable (use disp line number) c Continue running the program until the next breakpoint. d Delete all break points. q Quit debugging. set args set the args which will be passed to argv and argc of the a.out program.] How do I get a call graph & statistics of my program ---------------------------------------------------- gcc -pg hello.c compile the program hello.c with the profile option flag -pg. a.out execute your program & produces a file "gmon.out". man gprof explains the profiler program. gprof >stats reads the "gmon.out" file and outputs to the standard out and writes it to the file "stats". C Library tips -------------- The following is a list of how to use the libraries #include Uses no libraries, defines NULL, size_t, ... #include Uses no libraries, macros for isspace, ... #include #include #include #include gcc prog.c -lc #include gcc prog.c -lm yacc functions gcc prog.c -ll #include #include gcc prog.c -lX11 The libraries are abreviated. For example "-lc" stands for "/usr/lib/libc.a" Any C compiler will accept a list of libraries and will search each library from left to right. This means that if there are duplicate entries in various libraries then the first library it is found in is used; not the last. An example of a multiple list: gcc prog.c -ll -lc -lm -lX11 To view the table of contents of a library use the "ar" command which is described in "man ar". For example: "ar t /usr/lib/libc.a" will list it's table of contents. To sort "ar" to a four column twenty lines per page output: ar t /usr/lib/libc.a | sort | pr -4 -l20 | more maintain archive files ---------------------- ar rcv libaaa.a Create an "sequential" archive file libaaa.a ar rv libaaa.a file.o Add (replace) a file.o into the archive ranlib libaaa.a Make a random access archive file ** Must be done after each add/delete to be safe. ar t libaaa.a Display archive table of contents ar xv libaaa.a file.o Extract file.o and store as file.o in directory ar dv libaaa.a file.o Delete file.o within archive My first X windows program -------------------------- Compile the following code with the command: gcc xtest.c -lX11 -o xtest To execute: xtest -----------------------------xtest.c------------------------------------ #include #include #include #define FALSE 0 #define TRUE 1 /* Work Window */ typedef struct { Display *Display; Window Window; GC GC; XEvent XEvent; KeySym KeySym; XSizeHints XSizeHints; int screen; struct { int width, height; } device; struct { float xlow, xhigh, ylow, yhigh; } view; struct { float xlow, xhigh, ylow, yhigh; } window; } wwindow; /* Sets the color of the foreground. */ /* Of course, this only works for color machines. */ void WColor(wwindow *ww, char *colorname) { Colormap cmap; XColor color, exact; Status result; cmap =XDefaultColormap(ww->Display, ww->screen); result=XAllocNamedColor(ww->Display, cmap, colorname, &color, &exact); if (result) { XSetForeground(ww->Display, ww->GC, color.pixel); } } /* Draws a point at (x, y) */ void WPoint(wwindow *ww, int x, int y) { XDrawPoint(ww->Display, ww->Window, ww->GC, x, y); } /* Draws a line from (x1, y1) to x2, y2) */ void WLine(wwindow *ww, int x1, int y1, int x2, int y2) { XDrawLine(ww->Display, ww->Window, ww->GC, x1, y1, x2, y2); } /* x and y specify the center of the arc */ void WArc(wwindow *ww, int x, int y, int r, int theta1, int theta2) { XDrawArc(ww->Display, ww->Window, ww->GC, x-r, y-r, 2*r, 2*r, theta1*64, theta2*64); } void WFillPolygon(wwindow *ww, XPoint *points, int npoints) { XFillPolygon(ww->Display, ww->Window, ww->GC, points, npoints, Complex, CoordModeOrigin); } void WText(wwindow *ww, int x, int y, char *text) { XDrawImageString(ww->XEvent.xexpose.display, ww->XEvent.xexpose.window, ww->GC, x, y, text, strlen(text) ); } /* loops until you click on the window to continue */ void WPause(wwindow *ww) { int done; done = 0; while(done == 0) { XNextEvent(ww->Display, &(ww->XEvent)); switch(ww->XEvent.type) { case MappingNotify: XRefreshKeyboardMapping((XMappingEvent *)&(ww->XEvent)); break; case ButtonPress: done=1; break; } } } /* Clears all graphics of the window. */ void WClear(wwindow *ww) { XClearWindow(ww->Display, ww->Window); } /* x and y are the top left corner of the window. */ /* makes a window with black and white foreground. */ wwindow *WOpen(int x, int y, int width, int height) { int done; unsigned long foreground; unsigned long background; wwindow *ww; ww = (wwindow *)malloc(sizeof(wwindow)); if (ww==NULL) { fprintf(stderr, "WOpen: malloc error\n"); exit(1); } ww->device.width = width; ww->device.height = height; ww->Display = XOpenDisplay(""); ww->screen = DefaultScreen(ww->Display); background = WhitePixel(ww->Display, ww->screen); foreground = BlackPixel(ww->Display, ww->screen); ww->XSizeHints.x = x; ww->XSizeHints.y = y; ww->XSizeHints.width = width; ww->XSizeHints.height = height; ww->XSizeHints.flags = PPosition | PSize; ww->Window = XCreateSimpleWindow( ww->Display, DefaultRootWindow(ww->Display), ww->XSizeHints.x, ww->XSizeHints.y, ww->XSizeHints.width, ww->XSizeHints.height, 5, foreground, background ); XSetStandardProperties( ww->Display, ww->Window, "hello", "hello", None, NULL, 0, &(ww->XSizeHints) ); ww->GC = XCreateGC(ww->Display, ww->Window, 0, 0); XSetBackground(ww->Display, ww->GC, background); XSetForeground(ww->Display, ww->GC, foreground); XSelectInput(ww->Display, ww->Window, ButtonPressMask | KeyPressMask | ExposureMask ); XMapRaised(ww->Display, ww->Window); done = 0; while(done == 0) { XNextEvent(ww->Display, &(ww->XEvent)); switch(ww->XEvent.type) { case Expose: if (ww->XEvent.xexpose.count == 0) { done=1; } break; case MappingNotify: XRefreshKeyboardMapping((XMappingEvent *)&(ww->XEvent)); break; } } return(ww); } /* Closes the X window. */ void WClose(wwindow *ww) { XFreeGC(ww->Display, ww->GC); XDestroyWindow(ww->Display, ww->Window); XCloseDisplay(ww->Display); free(ww); } main(int argc, char *argv[]) { static XPoint points[5] = { {0,0}, {100,0}, {100,100}, {0, 100}, {0,0}}; wwindow *W; W=WOpen(100, 100, 500, 500); WLine(W, 10, 10, 100, 100); WLine(W, 10, 10, 20, 40); WLine(W, 10, 10, 40, 20); WLine(W, 10, 20, 100, 100); WLine(W, 10, 30, 100, 100); WLine(W, 10, 40, 100, 100); WPause(W); /* press mouse button to continue */ WClear(W); WColor(W, "coral"); /* use for color displays */ WArc(W, 100, 100, 100, 0, 90); WColor(W, "light steel blue"); WFillPolygon(W, points, 5); WPause(W); WClose(W); exit(0); } C interfacing tips ------------------ 1) Symbol table routines & clean interfaces a) All symbol table routines should be in a seperate file, say, for example, symtab.c. During compiler development this can placed in the beginning of the compiler file as #include "symtab.c" until the routines are stable. Then they can be seperately compiled and a "symtab.h" file is created. b) Generally the routines in a file of a common class should start with the same name, say SymFind, SymAdd, or SymOpen; for an include file for "SYMtab.c". c) Functions that are used internally to that class should be made "static". By default all functions are global and the keyword "static" makes that function private to that compilation. Static for data means something different than for a function. Static for data means that it is not created dynamically. d) Do not use a global variable for a symbol table, in fact minimize all your variables to be passed as arguments. f) Model your interfaces on what already exists in the standard C language routines. In particular, the symbol table functions should minic the file functions. For example, int fid = open(char *filename, int mode); int error = close(fid); int count = read(fid, char *data, int maxsize); int count = write(fid, char *data, int maxsize); or FILE *fp = fopen(char *filename, char *mode); int error = fclose(fp); ... then the symbol table routines can be modelled in the same way so that the programmer does not have to memorize so much. The programmer need only remember the style. Thus the symbol table functions look as such, typedef struct { char *id; int type; int address; int lineno; ... } SymEntry; typedef struct { SymEntry *next; ... } SYM; SYM *SP = SymOpen(HashSize, ....); int error = SymClose(SP); int error = SymWrite(SYM *SP, char *data, int size, char *key); int error = SymRead( SYM *SP, char *data, int size, char *key); int error = SymPrint(SYM *SP, FILE *fp); /* Print symbol table */ Notice that these routines look just like the file interfaces and with only the addition of the "search key" interface. This is a clean interface. g) DON'T use MULTIPLE symbol tables. For example, one for the keywords and one for the identifiers. Time is wasted if the string turns out not to be a keyword AND there is no need to write redundant routines. f) Make sure your symbol table tests for and handles overflow. Typically, overflows are written onto the disk. Also document this in your routines. Also explain clearly how collisions are handled. 2) When comparing characters avoid integers, yytchar == 10; /* wrong */ yytchar == '\n'; /* right */ 3) Switch statements test each case statement in a sequential order. Thus don't put your least probable case first. For example, if the test for -1 is rare and the case for 2 is expected to occur alot the put case 2 first. switch(type) { case -1: ....; break; /* wrong - this will always be tested first */ case 2: ....; break; } switch(type) { case 2: ....; break; /* good - most probable. */ case -1: ...; break; /* make this least probable. */ } Using "gcc -S program.c" will generate an assembly code output in "program.s". By experimenting, one can see what is efficient code or or not. 4) In ANSI C constant strings, can be broken up into seperate lines, so that one does not have to have a single line of 200 characters. Thus "abc" is equivalent to "a" "b" "c". During compile time, the compiler will concatenate them together as one string. Thus, you can now place them on seperate lines; remember to the compiler, blanks, tabs, and newlines are treated the same. 5) Error printing: write all errors to stderr. For example, fprintf(stderr, "line %d: ....", ...); 6) Error checking: Always test after each function if it was ok. For example, malloc(), returns a NULL if it is out of memory. And of course, write an error message to stderr AND if critical do an exit(1); Also, check for if identifiers exceed a certain length, say 31 characters, if you desire a limit. 7) Always use braces for "for", "if", "else" and "while" even for a single statement. And typedef all global structures. 8) For short statements, put them on a single line. if (error) { exit(1); } else { x=3; } 9) No Zig-Zag code: int x; /* wrong */ int x; /* right */ FILE *fp; FILE *fp; double f; double f; 10) Always use existing functions, don't re-invent the wheel. For example, the most common rewrite was strdup. Read the "/usr/include" directory and get familiar with "string.h", "stdio.h", "stdlib.h", etc. Also, count=sscanf(char *string, "%f", &float), will convert a character string into floating point routine. Notice, the clean and consistant interfaces of fprintf, sprintf, printf, and their inverse functions, fscanf, sscanf, scanf. improve your C style! [tips] ---------------------------- Helpful C Programming style and Documentation format. This is based on years of professional experience, and is called "defensive programming". There is nothing worst than to find out that an error was cause by a stupid mistake. The classic error is the indented if: if (x==3) y=3*a; printf("y=%y\n", y); if (x==7) z=2; If you observe that braces should be around the if statement! 1) One blank after each comma or semicolon. 2) Single statement conditional statements must be enclosed in parenthesis. For example, if (x==3) break; /* wrong */ if (x==3) { break; } /* correct */ while(--x); /* wrong */ while(--x) { } /* correct */ 3) No imbedded assigments: For example, while((c=getc())!=EOF) { ... } /* :-( wrong */ c=getc(); while(c!=EOF) { ... c=getc(); } /* :-) correct */ 4) No more than 7 levels of nesting. If nesting exceeda seven levels, create a subroutine for some of the nested code, or all of it. Also, a simple if can of the following forms, if (x==3) { y=3 * a; } else { z=2; } or, if (x==3) { y=3 * a; } else { z=2; .......; .......; .....; } Also, if the if statement cannot fit on a single line, the break it up as follows, if (x==3) { y=3 * a; ......; .......; ..........; ......; } else { z=2; .................................; .......; } 5) Indent nesting by every two blanks, no more and no less. 6) Left brace is not to be on seperate line. For example, main(int argc, char *argv[]) { /* :-( Wrong, wrong */ int i; ... } The correct way is, main(int argc, char *argv[]) { /* :-) correct */ int i; ... } /* it's easy to match this brace by the indent */ 7) Use ANSI C language ("gcc" not "cc" on unix ) For example, use the imbedded declarations main(argc, argv) int argc; char *argv[]; { /* :-( Wrong */ ... The correct way is, void main(int argc, char *argv) { Another major point, if a function does not return a value, you must use the void function (i.e. void main() { ). 8) Module Encapsulation: NO GLOBAL VARIABLES!!! Pass data via structures. For example, The wrong way is, FILE *FP, *FSTAT; /* :-( */ char *buffer; int count; x() { count++; } main() { count=0; x(); } The correct way is, which can be easily put in a include header file, typedef struct { FILE *FP; /* File pointer for input */ FILE *FSTAT; /* File pointer for statistics */ char *buffer; /* Input data buffer */ int count; /* Input character count */ } FileControl; /*--------------------------------------------------------------*/ /* x counts the number of characters. */ /* entry: FileControl block only using the input FP. */ /* returns: none */ /*--------------------------------------------------------------*/ void x(FileControl *FC) { FC->count++; ... } void main() { FileControl *FC; /* note: a blank line after declarations */ FC->count=0; x(FC); } 9) All declarations/definitions must have a comment. Functions, must be proceeded by a comment line (/*-----*/) from 1 to column 71. (as show above, using dashes not stars), with the following information: the name of the function, what is does, entry parameters, and return parameter. Variables if abbreviated which is good must be spelled out in the comment at the declaraction. Data comments should not be too vague (i.e. counter). 10) All structures must use typedef. 11) Typedef's, structures and functions should not be abbreviated, unless their usage is rare. Varibles may be abbreviated, in a common sense way, but in all cases, when they are declared, a comment must spell it out explicitly. Compound varibles can be formed in two ways, for example, compute_and_print=3; or ComputeAndPrint();. Using underscores is typically used for data variables and Upper/Lower case used for functions. The trend is depart from underscores. Rules for abbreviation, first remove the vowels, and then those letters in which the word can still be deduced. Compression of words can be stop at any level: Print, or Prnt, or Prt, or P. 12) No static structures within a program. It's okay to declare a static structure by then convert it to a pointer. This reduces software maintenance because when a program has to make the structure an argument to the function which commonly happens you don't have to edit the main body of the code only the declaration area. Also, the structure may have use a malloc() instead of static declaration which makes conversion simple. For example, main() { typedef struct { char *symbol; int offset; int lineno; } Record; Record Record; Record.offset=0; /* wrong way */ Record Record1, *Record=&Record1; Record->offset=0; /* correct */ 13) Bound loops: It is dangerous to write, for(i=0; i!=10; ++i) { ... } because the body of the loop may modify i beyond or below ten, and causing an almost infinite loop. Write all loops the following way, for(i=0; i>=0 && i<=10; ++i) { ... } 14) Do not use default proceedures, printf or getc, they cause maintence trouble; use fprint(stdout, ...) and fgetc(stdin). 15) Use stderr for printing error messages! fprintf(stderr, ...); 16) All messages must contain the name of the program using argv[0] which is passed by the shell to main. Also, the function in which the error occurred. For example, parser(Main *M, FileInterface *FI, TreeControlBlock *TCB) { : FP=fopen(FI->fname, "r"); if (FP==NULL) { fprintf(stderr, "%s/parser: Error cannot open file[%s]\n", M->argv[0], FI->fname); exit(1); } Note: The name of the program is first followed by a slash and the proceedure name. Also note, that strings of "unknown contents" have brackets around, so that any leading or trailing blanks/control characters can be seen. Error routines can be combined into a seperate function. Also notice, that the capitals are transferred into local declarations like FileInterface are defined as FI. 17) Do not use "do ... while(c)" constructs. All conditions must preceed a loop! 18) No Zig-Zags: all columns must nicely lined up! For example, filecontrol *FP; /* :-( Wrong, wrong and wrong */ int i; char c; The correct way is, filecontrol *FP; int i; char c; 19) Error messages are be broken down into the following groups, with their respective exit codes: 0, No errors or warnings detected Warning, 4, Possible errors (warnings) detected but execution should be successful. Hence, the program still runs perfectly but there might be some ambiguous statements which the user might want to be aware of. Error, 8, Serious error detected; execution likely to fail. Hence, the program will run but may fail under certain conditions. Typically, programs like these are still run during development time, when a programmer has not written all the proceedures and knows it will not crash under his usage. Or in business systems, a data file has been corrupted but the user is desperate and needs to get something out of it. Severe, 12, Severe error; execution impossible. Terminal, 16, Terminal (or internal error); execution cannot continue. For example, the compiler blew up (meaning crash) while compiling a program. Also, programs, have internal check points, like a dangling pointer, tree structure not in canonical form, etc., which means the program has a bug in it. 20) Splitting a large program into several includes. A single set of functions should not have more than 250-400 hundred lines in it. Also the property of a split program should maintain the superposition concept: gcc f == cat f1 f2 ... fn > f; gcc f Hence, each time you split, the include files must be included. #ifndef MAIN #define MAIN #include ... #endif Thus, each program file can be compiled seperately or used as an include file during development time. 21) It's okay to leave debugging statements in because a program is never debugged. Thus, one doesn't have constantly insert fprint statements in. The proper way is as follows, a variable starts with the word DEBUG followed by the function name. parser(...) { #ifdef DEBUGparser fprintf(stder, .......); PrintParseTree(....); #endif ... } Notice, if DEBUGparser is not declared the debug code is not compiled, which results in fast and efficient machine code. This is nice, when working on large systems in conjunction with the include files: ... #define DEBUGparser #define DEBUGoptimize #include <"parser.c"> #include <"optimize.c"> .... My first lex/yacc program -------------------------- The overall picture of lex/yacc +--------------------------------+ gcc -g -pedantic -c main.c | #include "y.tab.h" | | main() { yyparse(); } | ==> main.o +--------------------------------+ | | | y.tab.c +--------------------------------+ | yyparse() { | byacc -dv gram.y | ... | | while(token!=0) { | ==> y.tab.h | ...token=yylex()... | ==> y.tab.c | } | ==> y.output +--------------------------------+ | | | lex.c +--------------------------------+ | int yylex() { | lex -t lex.l > lex.c | ... | | c=input(yyin) | ==> lex.c | while(c!=0) { | | ...c=input(yyin)... | | ...return TOKEN;... | | } | | #define input(f) ...getc(f)... | | #define unput(c) ... | | | +--------------------------------+ | | | #include +--------------------------------+ gcc lex.c y.tab.c main.o -o compiler | int getc(FILE *fp) { | | ... | ==> compiler | } | +--------------------------------+ Lex functions ------------- int yylex() Returns the current token integer of the yyin character input stream. Token 0 is end of input. extern char *yytext; Contains the inputted (yyin) character string of the current token returned by yylex() function. extern int yyleng yyleng=strlen(yytext); extern int yylineno; Contains the current number of newlines (\n) read in by yylex(). extern FILE *yyin; Contains the current file pointer being used by lex. (default: stdin). ECHO; Debugging macro which prints out yytext to yyout; #define ECHO fprintf(yyout, "%s", yytext) BEGIN INITIAL; Begin lex from the beginning. (i.e. re-initialize lex's state machine to the beginning). BEGIN ; Begin at a particular state as defined inbetween %} and %%. To define a state %s . REJECT; Reject the current yytext and search for the next simular pattern match. This is used for overlapping matches: aaa, aab. extern FILE *yyout; Contains the current output debug file pointer being used by lex. (default: stdout). #define YYLMAX BUFSIZ is the maximum size of lex's character buffers. For example: char yytext[YYLMAX]; This is important when handing large tokens such as strings. WARNING: if token is larger than yytext then yylex will write all over memory! #define input(FILE *) macro which returns a character. If character is newline (\n) then increment yylineno. #define unput(char c) macro which puts a character back into the input buffer for lex to re-interpret. int yywrap() Called when yyin reaches end-of-file. If yywrap returns a zero (0) then yylex assumes real eof. yywrap can open another file for yylex and returns true (1). To use lex without yacc: ----------------------- main.c +--------------------------------------------------+ | extern FILE *yyin; /* lex input file */ | | extern int yylineno; /* current line number */ | | extern char *yytext; /* current token string */| | | | | | main{ | | int t, n; | | yyin = fopen(...); | | n=yylineno; t=yylex(); | | while(t!=0) { | | printf("line=%d token=%d string=%s\n", | | n, t, yytext); | | ... | | n=yylineno; t=yylex(); | | } | | fclose(yyin); | | } | +--------------------------------------------------+ lex.l +-------------------------------------+ | %{ | | /* user code */ | | /* redefine lex macros */ | | #define IF 258 | | #define INT 259 | | %} | | %% | | "if" { return IF; } | | [0-9]+ { return INT; } | | %% | | /* more user code */ | +-------------------------------------+ lex -t lex.l > lex.c gcc lex.c main.c -o compiler Types of lexical generators --------------------------- lex Traditional Unix lex {/usr/bin} flex Gnu Fast Lex {/usr/local/bin} yacc Traditional Unix yacc {/usr/bin} byacc Berkeley yacc {/usr/local/bin} {better & run on pc} bison Gnu yacc {/usr/local/bin} References ---------- Levine, John R. et. el., lex & yacc, O'Reilly & Associates, Inc, $29.95 My first Prolog program ----------------------- (1) First make sure your path is set to: /usr/lang/prolog/bin (2) Enter the following program via the unix editor, ed. ed hello.pl Start editor a editor command to add text until dot in column 1 main :- write(hello). . end of input, dot in column 1 and return w editor command to write text to unix file, hello.pl q editor command to quit editor sp Start Prolog [hello]. load prolog program, hello.pl, WARNING every command ends in a period!!! main. execute the query, main and the output should be hello. ^C Control C enters the prolog debugger. h is for help e exits the program t starts the trace for the NEXT prolog query. (1) First type t (2) Then type prolog query, main (3) each return single steps (4) to terminate type, a to abort. ^D Control D is an alternate way to exit the prolog program and return to Unix. My first LISP program --------------------- Using the Unix editor, ed, enter the following text. ed HELLO start editor, note UPPERCASE letters!!! a editor command to add text until dot in column 1 (defun main () (print '(hello world)) ) . end of input, dot in column 1 and return w editor command to write file out. q editor command to quit. gcl Start LISP interpreter (load 'HELLO) load HELLO file, all LISP files must be in UPPERCASE letters. (main) Execute main, output will be (hello world) ^D Control D to exit LISP program. My First LATEX document ----------------------- Latex is use for high quality documents for class reports, papers, etc. in the CES department. The output will go to the laser printer. Enter the following text wia the UNIX editor, ed hello.tex Start editor a editor command to add text until dot in column 1. \documentstyle{article} \title{hello world} \author{Francis Wolff} \begin{document} \maketitle \section{LATEX says hello} Hello, world. This is my first Latex document \end{document} . end of input, dot in column 1 and return. w editor command write text to file, hello.tex q editor command to quit editor and return to Unix. latex hello Start Latex output a hello.dvi file. dvi2ps hello | lpr -Palw2 Converts the hello.dvi to postscript and outputs it to the laser printer in Crawford. xdvi hello This is the X-windows previewer, type q to quit previewer. YOU must be running under xwindows (i.e. xinit). Other Latex commands -------------------- \tiny Change Type Size: all text following \tiny will be tiny. \scriptsize For example: \large abc { \small efg } hij \fontnotesize will print abc in large type, \small efg in small type, \normalsize hij in large type. \large Note: braces { ... } are for temporary modes. \Large \LARGE \huge \Huge \it italic type style, print following text in italic type style. \bf bold face type style. \rm roman type style, the default normal font \tt teletype type style, fixed width computer listing font. \sl slanted type style. \em emphazied type style. \sf San-sarif type style. \sc small capitals type style, convert to uppercase. Changing margins in Latex ------------------------- % The following code for 8.5"x11" is recommended by me (Michael Somos) % place this after \documentstyle \hoffset= -1in % horizontal origin = left edge of paper \voffset= -1in % vertical origin = top edge of paper \setlength{\textwidth} {6.5in} % width of body of text that you desire \setlength{\textheight} {9.0in} % height of body of text that you desire \setlength{\oddsidemargin}{1in} % the left margin (unless double sided) \setlength{\topmargin} {1in} % the top margin that you desire Spelling -------- look Unix command to check on how to spell a word, type spell and the word. The word does not have to be complete, it can even be the first letter. Spell will find the best matches. ispell -t hello.tex ispell is used to spell check .tex files. The speller stops at each unknown word and waits for an input command. command { explaination } ------- ------------------ x { exit ispell} ? { help menu } { accept word as correct this time only } a { accept word for rest of file } i { accept word as correct and insert in } { your private dictionary} r {replace the word} l { look up a word in the dictionary, } { type number IF you want to replace, } { otherwise type another ispell command } ^l { Control-L redraw screen } ! { execute a unix command } { inside ispell } Shell Management ---------------- Here is the shell history tree: sh c-shell | | korn shell t-shell | | +----------------+ | bash cshell ------ /bin/csh reads a hidden configuration file in your directory call ".cshrc". The "ls -a" command will display these hidden dot files. If you modify your configuration file and wish to update it without relogging in just use the "source" command. "source .cshrc" will cause the cshell to read in a new configuration file. "man csh" will give further information on usage. Changing from cshell to tshell ------------------------------ chsh Is used to change cshell to tshell old shell: /bin/csh This the old shell name; just hit the return key. new shell: /bin/tcsh Enter "/bin/tcsh" and return key for new shell. password: Enter your login password. The next you login (it requires 5-10 minutes to update the system) you will be using tshell tshell ------ tshell has a more power line editor. It rememebers previously typed commands. To recall these commands use the up & down arrow keys. A recalled line can also be edited by the left, right and delete keys. Ctrl-a Goto beginning of command line Ctrl-e Goto end of command line will display the previously typed command. repeating pressing will display more commands. will display more current commands. stty -a will display all the shell editing keys history will display all previously typed commands. !# will execute a previous command Example: history ... 32 ls -l ... !32 This will execute the 32nd history command rehash makes the shell aware of newly compiled programs for executing. Necessary, when compiling new programs that have the same name as the system executables. source .tschrc if you make changes in the shell configuration and don't want to re-login setenv Shows your environmental variables umask Shows your current file protection mask /bin/tcsh reads a hidden configuration file in your directory called ".tcshrc". The "ls -a" will display these hidden dot files. X-Windows --------- xinit This command will read the ".xinitrc" file and bring up the X-Window system. This requires that you have a path in your .cshrc or .tcshrc to be "/usr/bin/X11". startx SPARC station IPC: same as initx. X-windows initialization file: "~/.xinitrc" in your home directory ---------------------------------------------------------------- # WARNING: First character must be blank character! # is for comments. # .xinitrc # # This is invoked by xinit. # WARNING: The & must occur after every program except the last!!! # option -fn is font to be displayed. Use xfontsel to find others # option -geometry positions the screen of each program in pixels. # The format is: x++ # The Width & Length for emacs & xterm is number of char. # option -n This places the in the X-Window's title bar. # # xterm -xrm "*iconGeometry: 111x43+577+0" -iconic -geometry 50x30+3+60 -n console -display :0 -C & xclock -digital -fn *courier*bold-r*180-100* -geometry 380x35+0+0 & xterm -iconic -xrm *iconGeometry:66x43+503+0 -C -j -geometry 74x25+2+184 -n Unix -fn *courier*bold-r*180-100* & xbiff -update 700 -geometry 125x40+900+0 & x11emacs -fn *courier*bold-r*180-100* -w 80x15+150+150 -geometry 76x35+2+50 & twm X-window applications --------------------- xdvi sample.dvi will display a "latex sample.tex" file on the graphics display. xfig Graphics software to draw figures and import into Latex files. xmath Mathematica software. xgif picture.gif will display a color or black & white "picture.gif". xview view bit images (Sun 3/60 only). xv Newer version of xview. xv -root file.gif Will display a binary image file (.gif) onto the screen background. To dump an image of an X window { Joan Carletta} ------------------------------------------------ In some other window, type: xwd > Now, click the rightmost mouse button on top of the window you'd like to capture. You will hear three beeps. The created file is in a special window dump format. To convert this format to postscript, type: xpr -device ps -output .ps -portrait -compact This command has many other options, e.g. "-landscape" for landscape mode instead of portrait mode, "-rv" for reverse video. This postscript file can now be viewed using any postscript viewer, e.g.: gs .ps or printed: lpr -Palw2 .ps How to kill X-windows when you are locked up -------------------------------------------- (1) Suppose your X-windows systems is locked up. Say machine, beryl. (2) logon: First login on another workstation, say diamond, using the same login name & password (3) rsh beryl Remote login to the machine where you had trouble (4) ps This displays all the processes running under your login account on the workstation beryl. (5) kill -9 Look at the numbers from the "ps" and start killing all the processes until the X-windows shuts down. Also check ps. Be careful not to kill yourself. (6) ^D logout, of the remote shell & logout of diamond. (7) ^D go to the first workstation, beryl, and logout there. X-Windows basic systems ----------------------- ghostview Postscript viewer netscape Internet browser: integrated ftp, http, telnet, archie postscript and html viewers. mosaic Internet browser: first browser ever made. xbiff Graphic icon (mailbox) lets you know when you have received mail. xclock Graphic icon to display the time. xcalc calculator. xdvi Device Independant viewer from latex output xfontsel will display all the built in fonts in the current X-Window system. By using the mouse, pick each of the subfield in the xfontsel: fmly for family font, ptSz for point size, etc. until you have reached "1 font match" in the upper right hand of the screen." The font name, "*courier*bold-r*180-100*" you will have to type into your .xinit file for each entry -fn *courier*bold-r*180-100*. x11emacs X windows version of emacs. xlock Temporarily lock up your workstation display. The screen waits for a password. xman The unix on-line manual. xplaces will display all the positions of your current windows and icons. This is used for setting up your .xinitrc file so the windows comeup in the position where you want it. xspread Spreed sheet like Lotus 1-2-3 or Excel. xterm create a vt100 console window. xv Picture viewer for .gif twm Tom's Window Manager: This reads the .twmrc file fvwm Virtual window Manager Common file types ----------------- *.c C Language file: use the unix "gcc", "g++", or "cc" command. *.C C++ language file: use "g++ file.C" *.h C/C++ include files (i.e. include stdio.h) *.o Compiler object file: use "nm a.out | more" lib*.a archived library file: use "ar t libc.a | more" *.dvi Device Independant file: generated by the "latex" or "tex" program: use "xdvi file.dvi" *.gif Grapfics file: use the "xgif" file or "xv file.gif" *.gz GNU compressed file: use "gunzip file.gz" *.lex Compiler lexical language use: "flex file.lex" *.yacc Compiler grammar language use: "bison file.yacc" or "yacc file.yacc" or "byacc file.yacc" *.ps Postscript file use "ghostview file.ps" *.pl prolog file *.tar Tape Archived file: unix "tar xvf file.tar" command. *.tex Tex file: used by "latex" and "tex" *.z Compressed file by the unix "pack" command. Use "unpack" to restore. *.zip Compressed file. Use "unzip file.zip" to decompress. *.Z Compressed file by the unix "compress file.Z" command. use "uncompress *.Z" to restore. Special Filenames ----------------- a.out Executable binary file: generated by a compiler. core Memory image when your program failed. Do "rm core" gmon.out statistics generated by a program "gcc -pg" use "gprof". mbox Mail box: contains unsaved mail .xinitrc This is the X-window configuration file located in the user's home directory {"ls -a" shows all hidden dot files } .plan This file is read (if it exists) by the remote a finger. .project Also used by finger. .newsrc This contains all the news group used by the "rn" command. .cshrc This is the c-shell configuration file. .tcshrc This is the t-shell configuration file. .bashrc This is the Bash configuration file. .history a history of the commands you typed .netscape-history netscape: where you have been on the net .netscape-bookmarks.html Netscape saved bookmarks .mosaic-global-history file transfer notes (This is old but useful knowledge: best use netscape) ------------------------------------------------------------------------- Using the Unix on-line Manual ----------------------------- man { This command will give details on any Unix command } man man { This explains about the manual itself } The manual is for more details of the following topics to be discussed here. ---------------------------------------------------------------------------- man mail { The manual on electronic mail } man uuencode { The manual on encoding/decoding binary files } man ftp { The manual on File Transfer Program } man compress { The manual for compressing/uncompressing files } gzip -h { help on gzip compression program } man tar { The manual for archived files } man telnet { The manual on Telnet } man script { The manual on saving text going to the display } Printing the manual to the printer ---------------------------------- man uuencode > zzztemp { This will copy the manual information of } { "uuencode" to a file for example "zzztemp" } lpr zzztemp { This will print the file zzztemp } rm zzztemp { This will remove the file zzztemp } Using Electronic-Mail --------------------- To send a file "letter.dat" to mcintyre --------------------------------------- mail mcintyre@cis.csuohio.edu reads in a file } Thanks. . { period in column 1 and carriage } { return, ends the input. } Using mail commands directly in a file -------------------------------------- Note: all mail commands (i.e. ~) can be include in a file and do not have to be executed from the console. This is shown below: ed letter.dat { line editer of a new file "letter.dat" } a { append to the file; start console input } ~s Latest Software { ~s set the mail subject header } Dear Sir, Here it is. ~r calc.c { ~r insert a file when mailing } Thank you. . { period in column 1 and return, ends input } w { write the edit buffer to the file } q { quit the editor } mail mcintyre@cis.csuohio.edu < letter.dat { now mail this file and } { ~r will now take effect } uuencode: Binary Mail Transmission ---------------------------------- Mail can only send ascii files (decimal 10, 32 to 127). This is typically used for transmitting machine executable code (i.e. load modules) and pictures such as *.gif and *.jpg files. uuencode is used to convert a binary file for e-mail into ascii text. For example, to convert a file "a.out" to ascii text file "a.out.uu": uuencode a.out a.out >a.out.uu Note: the first argument is the actual input file "a.out" the second argument is a name that is placed inside the output file (stdout) "a.out.uu" This second argument will be used by the decoder, uudecode, as the actual destination name. The contents of "a.out.uu" will look as follows: begin a.out MAHGTYROD{DK23409827400*)(*)(*)(*U424U341 MLASKJDFLAKS2093840S123124567457*&^^$#@%$ MKWEPORPWOEKRPOWEKRPOWEKRP.............LA end Note: This file has a begin and end. All other lines start with "M" in column one and 64 characters in length. This file can now be processed a regular text file and is commonly broken up into smaller files and sent through e-mail in pieces since e-mail does not like files larger than 64000 bytes. uuencode takes every 3 binary bytes and converts it to 4 ascii characters. Thus the final file will only increase by 25%. The first character in column one (i.e. M) represents the binary length + hex 20, followed by the encoded binary text. Now, we can mail this file: --------------------------- mail -s "sending a.out.uu" macintyre@cis.csuohio.edu { type letter on the terminal and make this the } { current letter } s { save the current letter in a file } d { delete the current letter } q { quit mail, don't worry nothing will be lost. } ? { help command, display all commands } additional, no so common commands s { save letter number in a file } d { delete a letter number } finger: Check if a person is logged on, last mail, or .plan ----------------------------------------------------------- If you are not should if the person has read your mail, finger is used. To check follow these steps: (1) finger , and note the last read mail time, (2) mail -v , the -v option verifies the transmission route, if far away messages will appear on your screen over several hours, letting you know over each network it has passed. (3) finger again, the read mail time should change. (4) The next day, the LAST READ MAIL should be greater than the in step (1) or (3), if not the user has not read your mail yet. finger for example, finger wolff@alpha.ces.cwru.edu (1) LAST LOGON: The finger will display the last logon for the remote machine the user has been on. So even if the user has not logged-on it is for that machine you are fingering. You will have to finger the user at another machine. (2) LAST READ MAIL: The finger will display the last time the user has read mail. This is a good indicator of the last time the user has logged-on on any machine because this assumes that everytime a user logs-on the user read their mail but this is not always true. (3) .plan FILE: The finger will read the .plan in the user's home directory. Typically the user will place the office hours and research interests. Since Unix treats any file as hidden, to list dot files, just type, "ls -a". You can make your own .plan file using any ascii editor. talk: Interactive talking in RealTime ------------------------------------- This program allows a user talk to another logged-on user around the world via internet. (1) Make sure the environmental variable TERM is set to vt100. check it by typing "setenv". If not then set it by typing, "setenv TERM vt100". Of course your environment should be to support a vt100 (X-windows does, almost all PC-Based modem software) (2) Now type, talk If the remote user is logged-on it should tell the remote user to type talk . Use "finger" as a double check. If talk does not work, try, "ntalk". (3) Once contact has been made, each talk user will see their screen split into two halfs, the top is for the caller to type, and the bottom is for the receiver. So type away. (4) Control D or Control C will terminate the talk. write: Write text to a remote user ---------------------------------- (1) write (2) write . {period in column one} for example, ------------ write wolff hello, how are you or if not on the same domain, ----------------------------- write wolff@alpha hello how are you or if very far away ------------------- write wolff@alpha.ces.cwru.edu hello how are you ftp: file transfer program -------------------------- This program allows a user to connect to computers around the world and transfer files between computers. To get a file from a remote machine ----------------------------------- ftp open info.umd.edu { open a connection to the University of } { Maryland. } login: anonymous { login: is display once a connection is } { made. The user types "anonymous". } password: anonymous { Depending on the message from the remote } { system: type "anonymous" or "ident" } ls { This will list the directory of the } { of the remote system. } cd /pub { This will change the remote directory } { to "/pub" } get zzz { This will copy exactly one file from the } { remote system called "zzz" into your } { local directory with the same name. } quit { This will close the connection and exit ftp } Other ftp commands of interest ------------------------------ ls -l { list long format of remote directory } ls p* { list all programs beginning with "p" } mget * { Multiple Get: will copy more than one } { file(s) to your local system. } mget *.c { Multiple Get all files ending in ".c" } lcd { Local Change Directory (i.e. your system) } ! { execute local commands: } { "!cd" does not work, always use "lcd" } ? { list all ftp commands } A short list of anonymous ftp sites ----------------------------------- info.umd.edu { News, weather, Project Guttenberg, books, Bible } prep.ai.mit.edu { Souce code of C, C++, lex (flex) compilers } wuarchive.wustl.edu { IBM PC software & archive almost all software } research.att.com { Fortran Code, and Fortran to C } rexx.uwaterloo.ca { Source code of Rexx compiler } primost.cs.wisc.edu { Comp.compiler news group back issues & grammers } okeeffe.berkely.edu { Source of YACC } File.Z: compressed files ------------------------- Many files at ftp sites are compressed and have a filetype of ".Z". The uncompress command will uncompress a "file.Z" into "file" and dropping the ".Z" in the process. uncompress file.Z (standard unix compression format) gunzip file.Z (unix compression format) gunzip file.gz (gzip compression format) File.tar: extracting Tape ARchived files ----------------------------------------- An Archive file implies it contains many files and directories. Extracting an archive file will typically create sub-directories and many files. The tar command will extract files and will not delete the original file "file.tar". tar tf file.tar (list all filenames in a tar file) tar xvf file.tar (extract all files from tar file) File.tar.Z: compressed tape archived file ----------------------------------------- This is very common file format at ftp sites. First, uncompress the file and then extract the file. A safe method is to first copy the file into an empty directory. Here are the various ways for different formats: zcat file.tar.Z | tar xvf - (standard unix compression format) gzcat file.tar.Z | tar xvf - (standard unix compression format) gzcat file.tar.gz | tar xvf - (gzip compression format) Warning: extracting will use up a lot of disk. Making compressed and tar files ------------------------------- tar cvf filename.tar * { Create an archive file for all files "*" } { in the current directory. Please add ".tar"} { to the filename since the "tar" does not. } compress filename.tar { "filename.tar" will be compressed and the } { resulting file will be "filename.tar.Z" } Archie: Database for software ftp sites --------------------------------------- Archie is a database which contains locations of most of the software locations. telnet open quiche.cs.mcgill.ca { Open a connection to Canada. } login: archie { Enter in "archie" after the "login:" prompt } help { optional: will explain archie briefly. } prog pascal { This will find all software related to } { "pascal" and display them on the terminal. } prog compiler { This will find all software related to the } { pattern "compiler". } quit { This will close the connection and exit telnet } Others archie sites, if mcgill is too busy: archie.rutgers.edu 128.6.18.15 (Rutgers University) archie.sura.net 128.167.254.179 (SURAnet archie server) archie.unl.edu 129.93.1.14 (University of Nebraska in Lincol n) archie.ans.net 147.225.1.2 (ANS archie server) archie.au 139.130.4.6 (Australian server) archie.funet.fi 128.214.6.100 (European server in Finland) archie.doc.ic.ac.uk 146.169.11.3 (UK/England server) archie.cs.huji.ac.il 132.65.6.15 (Israel server) archie.wide.ad.jp 133.4.3.6 (Japanese server) archie.ncu.edu.tw 140.115.19.24 (Taiwanese server) script: Saving Text going to the display ---------------------------------------- When using telnet, it will display hundreds of pattern matches due to the "prog" command. Thus to save this infomation, one must use the "script" command which saves all keyboard & display (i.e stdin & stdout) into a file. script zzztemp { start saving display data (i.e. stdout) in file zzztemp } telnet { start your telenet } ....... { login, prog, commands } quit ^D { Stop collecting display data } ...... { edit zzztemp file removing unwanted text and then } { print it (lpr) or down load it to a personal computer } rm zzztemp { remove the zzztemp file } If you have a home computer --------------------------- Use FreeNet: 368-3888 and set up your own e-mail account. kermit: uploading/downloading files to a personal computer ---------------------------------------------------------- Kermit is a program on almost all machines which allow to tranfer files from a mainframe to a personal home computer. The personal computer requires a vt100 terminal emulator (such as Pibterm, which is available free from Cleveland State University Computing Services Center, 687-2183 or 687-2000). To download a file from Unix to the pc, kermit { Start communications program } ? { Optional: help command } show { Optional: displays modem and bit settings } set parity even { Only if you phoned in with even. by default no parity } send { Send a file on a Unix system to pc } .... { Now setup your personal computer to receive a file via } { kermit. For pibterm, it is ALT-R for receive mode. } quit { This is after the file is transfered quit the kermit } To upload a file from the pc to Unix, kermit receive .... { Now setup your personal computer to send a file via } { kermit. For pibterm, it is ALT-S for send mode } quit