Software Tools & Systems Programming In UNIX

2y ago
12 Views
2 Downloads
423.63 KB
270 Pages
Last View : 11d ago
Last Download : 3m ago
Upload by : Kaden Thurman
Transcription

CSC209Software Tools & SystemsProgramming in UNIXW. James MacLeanmaclean@cdf.toronto.eduLP290F, 978-6277

About CSC209

Slide 3General Info Meets Tuesday & Thursday, 1pm in RW117 Tutorials Fridays at 1pm (rooms TBA) Website:http://www.cs.toronto.edu/ maclean/csc209/Fall99 Newsgroup:ut.cdf.csc209Fall 1999CSC209: Software Tools & Systems Programming

Slide 4Assignments Assignment #1: 5% Fri, Oct 8th– Shell Scripts Assignment #2: 10% Fri, Oct 29th– Utilities, File/Directories Assignment #3: 10% Fri, Nov 19th– Inter-process communication Assignment #4: 15% Fri, Dec 10th– Sockets & ThreadsFall 1999CSC209: Software Tools & Systems Programming

Slide 5 Assignments are due at the beginning oftutorials. Late assignments should be submittedto D.L. Pratt Bldg., room 283. Penalties for latesubmissions: Time of submission (based on electronic submission time): by 5pm on due date - penalty - 20% (of the maximummark) by 9am three days after due date - penalty - 40% after 9am three days after due date - penalty - 100% The late penalties are only waived for a goodreason such as a documented medical or otheremergency. Discuss such excuses with theinstructor, not with your tutor.Fall 1999CSC209: Software Tools & Systems Programming

Slide 6Plagiarism The work you submit must be yourown, done without participation byothers. It is an academic offence tohand in anything written by someoneelse without acknowledgement.Fall 1999CSC209: Software Tools & Systems Programming

Slide 7Tutorials A — Hua, Jamie Ho, RW117, jamie@cs Hui — Pre, Kevin Hui, SS2111,at209hui@cdf Pu — Z, Olga Kundzich, SS1070,kundzich@interlog.com Lab Hours: Announced in advance of eachassignment due date, take place in EA107Fall 1999CSC209: Software Tools & Systems Programming

Slide 8Contacting Me Office Hours:– Tuesdays, 4-5 pm, D.L. Pratt Bldg. 290F– by special appointment Via e-mail:– maclean@cdf.toronto.edu– Important! Include "CSC209" in subject line Via phone:– 978-6277 (I check messages only on days I'm in)Fall 1999CSC209: Software Tools & Systems Programming

Slide 9Important Dates Last day to enrol: September 24th, 1999Last day to drop: November 5th, 1999Last class: December 9th, 1999Midterm: October 26th, 1999 (in class)Exam: TBA (schedule out Oct 22nd)Fall 1999CSC209: Software Tools & Systems Programming

Slide 10Reference Material An introduction to UNIX, Paul S. Wang UNIX System Programming,Haviland/Gray/Salama Programming with POSIX Threads, DavidButenhof Lecture Notes Advanced Programming in the UNIXEnvironment, Richard StevensFall 1999CSC209: Software Tools & Systems Programming

Slide 11Reference Material (2) The C Programming Language, 2nd Ed.,Kernighan & Ritchie Managing Projects with Make, Oram/Talbott UNIX for Programmers and Users, 2nd. Ed.,Glass/Abels UNIX Network Programming, RichardStevensFall 1999CSC209: Software Tools & Systems Programming

Slide 12Course Content Why UNIX? History UNIX Basics: Processes, Login Shells: command processing, runningprograms, shell programming I/O: file descriptors vs. streams Processes: creating, destroying, monitoring System Calls, Standard C LibraryFall 1999CSC209: Software Tools & Systems Programming

Slide 13 File/directory manipulation Signals Pipes, Sockets, Inter-processcommunication Multiplexed I/O Shared Memory, Semaphores POSIX Threads Concurrency: Race Conditions, Deadlock,Postponement, Producer-Consumer Project ManagementFall 1999CSC209: Software Tools & Systems Programming

Slide 14Some Self Study Topics Standard UNIX UtilitiesWriting MAN pages'C' RefresherString Handling in 'C'Fall 1999CSC209: Software Tools & Systems Programming

Section IUNIX FOR THE USER

Slide 16What is UNIX good for? Supports many users running many programs atthe same time, all sharing (transparently) the samecomputer system Promotes information sharing More than just used for running software geared towards facilitating the job of creating newprograms. So UNIX is “expert friendly” Got a bad reputation in business because of thisaspectFall 1999CSC209: Software Tools & Systems Programming

Slide 17History (Introduction) Ken Thompson working at Bell Labs in 1969 wanted a smallMULTICS for his DEC PDP-7 He wrote UNIX which was initially written in assembler and couldhandle only one user at a time Dennis Ritchie and Ken Thompson ported an enhanced UNIX to aPDP-11/20 in 1970 Ritchie ported the language BCPL to UNIX in 1970, cutting it down tofit and calling the result “B” In 1973 Ritchie and Thompson rewrote UNIX in “C” and enhanced itsome more Since then it has been enhanced and enhanced and enhanced and See Wang, page 1 for a brief discussion of UNIX variations POSIX (portable operating system interface) - IEEE, ANSIFall 1999CSC209: Software Tools & Systems Programming

Slide 18Some Terminology Program: executable file on disk (machine language binary or script) Process: executing instance of a program Process ID: unique, non-negative integer identifier (a handle by whichto refer to a process) UNIX kernel: a C program that implements a general interface to acomputer to be used for writing programs System call: well-defined entry point into kernel, to request a service UNIX technique: for each system call, have a function of same name inthe standard C library– user process calls this function– function invokes appropriate kernel serviceFall 1999CSC209: Software Tools & Systems Programming

Slide 19Logging in Login name, password System password file: usually “/etc/passwd” /etc/passwd has 7 colon-separated fields:maclean:x:132:114:James MacLean: 1 2 3 4 5 /u/maclean:/var/shell/tcsh 6 7 1: user name5: “in real life”2: password (hidden)6: HOME3: uid7: shellFall 1999 4: gidCSC209: Software Tools & Systems Programming

Slide 20Shells Bourne shell, C shell, Korn shell, tcsh– command line interpreter that reads user input and executes commands ls -l /var/shelltotal 6lrwxrwxrwx 1 root/usr/bin/cshlrwxrwxrwx 1 root/usr/bin/kshlrwxrwxrwx 1 root/local/sbin/newshlrwxrwxrwx 1 rootlrwxrwxrwx 1 root/local/bin/tcshFall 199912 May 15 1996 csh - 12 May 15 1996 ksh - 17 May 15 1996 newsh - 11 May 15 1996 sh - /usr/bin/sh15 May 15 1996 tcsh - CSC209: Software Tools & Systems Programming

Slide 21newsh “man page”newshnewsh - shell for new usersSYNOPSISnewshDESCRIPTIONnewsh shows the CDF rules, runs passwd to force the user tochange his or her password, and runs chsh to change theuser's shell to the default system shell (/local/bin/tcsh).FILES/etc/passwdSEE ALSOpasswd(1), chsh(1)HISTORYWritten by John DiMarco at the University of Toronto, CDFFall 1999CSC209: Software Tools & Systems Programming

Slide 22Files and Directories UNIX filesystem is a hierarchical arrangement of directories & files Everything starts in a directory called root whose name is the singlecharacter / Directory: file that contains directory entries File name and file attributes– type– size– owner– permissions– time of last modificationFall 1999CSC209: Software Tools & Systems Programming

Slide 23Files: an example stat /u/macleanFile: "/u/maclean" - "/homes/u1/maclean"Size: 17Allocated Blocks: 0Filetype: Symbolic LinkMode: (0777/lrwxrwxrwx)Uid: (0/Gid: ( 1/ other)Device: 0/1 Inode: 221Links: 1Device type: 0/0Access: Sun Sep 13 18:32:37 1998Modify: Fri Aug 28 15:42:09 1998Change: Fri Aug 28 15:42:09 1998Fall 1999root)CSC209: Software Tools & Systems Programming

Slide 24Directories and Pathnames Command to create a directory: mkdir Two file names automatically created:– current directory (“.”)– parent directory (“.”) A pathname is a sequence of 0 or more file names, separated by /,optionally starting with a /– absolute pathnames: begins with a /– relative pathnames: otherwiseFall 1999CSC209: Software Tools & Systems Programming

Slide 25Working directory Current working directory (cwd)– directory from which all relative pathnames are interpreted Change working directory with the command: cd or chdir Print the current directory with the command: pwd Home directory: working directory when we log in– obtained from field 6 in /etc/passwd Can refer to home directory as maclean or HOMEFall 1999CSC209: Software Tools & Systems Programming

Slide 26"pushd" and "popd" Makes directory navigation easier pushd pushes CWD directory pathname onto a stackmaintained by the shell popd pops a directory pathname from the same stack andmakes it the CWD Example:% pwd/usr/bin% pushd /; pwd /usr/bin% popd; pwd/usr/binFall 1999CSC209: Software Tools & Systems Programming

Slide 27Permissions When a file is created, the UID and GID of the creator are remembered Every named file has associated with it a set of permissions in the formof a string of bits:rwxs rwxs rwxowner group othersmoderegulardirectoryrreadlist contentswwritecreate and removexexecutesearchssetuid/gid n/a setuid/gid executes program with user/group ID of file’s owner Use chmod to change permissionsFall 1999CSC209: Software Tools & Systems Programming

Slide 28Input and Output File descriptor– a small non-negative integer used by kernel to identify a file A shell opens 3 descriptors whenever a new program is run:– standard input (normally connected to terminal)– standard output– standard error Re-direction:ls file.listFall 1999CSC209: Software Tools & Systems Programming

Slide 29Basic UNIX Toolsman ("man -k", "man man") (1.13)ls -la ("hidden files")cdpwddu, dfchmodcp, mv, rm (in cshrc: "alias rm rm -i" . )mkdir, rmdir (rm -rf)diffgrepsortFall 1999CSC209: Software Tools & Systems Programming

Slide 30More Basic UNIX Toolsmore, less, cathead, tail, wccompress, uncompress,gzip, gunzip, zcatlpr, lpq, lprmquota -v a209xxxxpquota -v a209xxxxlogout, exitmail, mh, rn, trn, nnwho, fingerdate, passwdFall 1999CSC209: Software Tools & Systems Programming

Introduction to theC Shell

Slide 32What is the Shell? A command-line interpreter program that is theinterface between the user and the OperatingSystem. The shell:– analyzes each command– determines what actions to be performed– performs the actions Example:wc -l file1 file2Fall 1999CSC209: Software Tools & Systems Programming

Slide 33csh Shell Facilities Automatic command searchingInput-output redirectionPipelining commandsCommand aliasingJob controlCommand historyShell script filesFall 1999CSC209: Software Tools & Systems Programming

Slide 34I/O Redirection stdin (fd 0), stdout (fd 1), stderr (fd 2) Redirection examples: ( , , , &, !, &! )fmtfmt personal letterfmt new filefmt personal letter new filefmt personal letterfmt personal letter & new filefmt ! new filefmt &! new fileFall 1999CSC209: Software Tools & Systems Programming

Slide 35Pipes Examples:who wc -lls /u/csc209h & sort -r For a pipeline, the standard output of thefirst process is connected to the standardinput of the second processFall 1999CSC209: Software Tools & Systems Programming

Slide 36Filename Expansion Examples:ls *.crm file[1-6].?cd /binls culhane*?[.][.-.][!.]Fall 1999Matches any string (including null)Matches any single characterMatches any one of the enclosed charactersMatches any character lexically between the pairMatches any character not enclosedCSC209: Software Tools & Systems Programming

Slide 37Command Aliases Examples:alias md mkdiralias lc ls -Falias rm rm -i\rm *.ounalias rmaliasalias mdalias cd 'cd \!*; pwd'Fall 1999CSC209: Software Tools & Systems Programming

Slide 38Job Control A job is a program whose execution has been initiated by theuser At any moment, a job can be running or stopped (suspended) Foreground job:– a program which has control of the terminal Background job:– runs concurrently with the parent shell and does not takecontrol of the keyboard Initiate a background job by appending the “&” metacharacter Commands: jobs, fg, bg, kill, stopFall 1999CSC209: Software Tools & Systems Programming

Slide 39Some Examplesa b c– connects standard output of one program to standard input of another– shell runs the entire set of processes in the foreground– prompt appears after c completesa & b & c– executes a and b in the background and c in the foreground– prompt appears after c completesa & b & c &– executes all three in the background– prompt appears immediatelya b c &– same as first example, except it runs in the background and promptappears immediatelyFall 1999CSC209: Software Tools & Systems Programming

Slide 40nice, nohup nice (csh built-in) sets the priority level of a command. The higherthe priority number, the slower it will run. Usage: nice [ n - n ] command Example:nice 20 emacs &nice -20 importantJob only root can give negative value nohup (csh built-in) makes a process immune to hangup conditions Usage: nohup command Example:nohup bigJob & in /.logout: /usr/bin/kill -HUP -1 & /dev/nullFall 1999CSC209: Software Tools & Systems Programming

Slide 41The History Mechanism Example session:alias grep grep -igrep a209 /etc/passwd ! /listhistorycat /list!!!2!-4!c!c newlistgrpe a270 /etc/passed wc -l pe epFall 1999CSC209: Software Tools & Systems Programming

Section IISHELL SCRIPTING

Slide 43Core Functionality of Shells built-in commandsvariableswildcards (file name expansion)background processingscriptsredirectionpipessubshellscommand substitutionFall 1999CSC209: Software Tools & Systems Programming

Slide 44Executables vs. Built-ins Most UNIX commands invoke utility programs that are stored asexecutable files in the directory hierarchy Shells also contains several built-in commands, which it executesinternally Type man shell builtins for a partial listing Built-in commands execute as subroutines, and do not spawn a childshell via fork()– Expect built-in (e.g. cd) to be faster than external (e.g. ls)Built-In:Non-Built-In:cd, echo, jobs, fg, bgls, cp, moreFall 1999CSC209: Software Tools & Systems Programming

Slide 45Variables Two kinds of variables:– local– environment Both hold data in a string format Main difference: when a shell invokes another shell, thechild shell gets a copy of its parent’s environmentvariables, but not its local shell variables Any local shell variables which have correspondingenvironment variables (term, path, user, etc.) areautomatically inherited by subshellsFall 1999CSC209: Software Tools & Systems Programming

Slide 46Variables (cont.) Local (shell) variables:– Simple variable: holds one value– List variable: holds one or more values– Use set and unset to define, delete, and list values Environment variables:– Use setenv and printenv to set and list values– All environment variables are simple (ie: no listvariables compare shell variable path toenviroment variable PATH )Fall 1999CSC209: Software Tools & Systems Programming

Slide 47Shell Scripts Shell scripts are just files containing shellcommands to be executed also make use of shell flow-controlstructures such as if else, foreach,etc. like a simple programFall 1999CSC209: Software Tools & Systems Programming

Slide 48Startup Files Every time csh is invoked, HOME/.cshrc isread, and contents of the file are executed If a given csh invocation is the login shell, HOME/.login will also be read and itscontents executed csh -f starts a shell without reading initializationfiles opening a new xterm -ls under X-windows willopen a new login shellFall 1999CSC209: Software Tools & Systems Programming

Slide 49Sourcing files Assume you create a file called “my aliases” Typing csh my aliases executes the lines in this file, but itoccurs in the forked csh, so it will have no lasting effect on theinteractive parent shell Correct method is to use the source command:source my aliases Common setup:– put all aliases in a file called HOME/.alias– add the line “source .alias” to the last line of HOME/.cshrcFall 1999CSC209: Software Tools & Systems Programming

Slide 50Input Processing When a input is typed, it is processed asfollows:–––––history substitutionalias substitutionvariable substitutioncommand substitutionfile name expansionFall 1999CSC209: Software Tools & Systems Programming

Slide 51Command Substitution Can substitute the output from a commandinto the text string of a commandset dir pwd set name pwd /test.cset x /bin/ls -l file Fall 1999CSC209: Software Tools & Systems Programming

Slide 52Shell Variables(setting) Examples:set Vset V abcset V (123 def ghi)set V[2] xxxxsetunset VFall 1999CSC209: Software Tools & Systems Programming

Slide 53Shell Variables(referencing and testing) Examples:echo termecho {term}echo V[1]echo V[2-3]echo V[2-]set W {V[3]}set V (abc def ghi 123)set N #Vecho ?nameecho {?V}Fall 1999CSC209: Software Tools & Systems Programming

Slide 54Shell Control bernogloba given with tcshmy favourite: set prompt “%m:% %#”disables Ctrl-D logoutnumber of previous commands retainedhow often to check for new maillist of directories where csh will look for commands (†)protects from accidentally overwriting files in redirectionturns off file name expansion Shell variables should not to be confused with Environment variables.Fall 1999CSC209: Software Tools & Systems Programming

Slide 55Variable Expressions Examples:set list1 (abc def)set list2 ghiset m ( list2 list1)@ i 10# could be done with “set i 10”@ j i * 2 5@ i comparison operators: , ! , , , , , , ! Fall 1999CSC209: Software Tools & Systems Programming

Slide 56File-oriented ExpressionsUsage:-option filenamewhere 1 (true) is returned if selected option is true, and 0 (false) amefilenamefilenameTest if filename can be readTest if filename existsTest if filename is a directoryTest if filename can be written toTest if filename can be executedTest if you are the owner of filename See Wang, table 7.2 (page 199) for moreFall 1999CSC209: Software Tools & Systems Programming

Slide 57csh Script Execution Several ways to execute a script:1) /usr/bin/csh script-file2) chmod u x script-file, then:a) make first line a comment, starting with “#”– (this will make your default shell run the script-file)b) make first line “#!/usr/bin/csh”– (this will ensure csh runs the script-file, preferred!) Useful for debugging your script files:“#!/usr/bin/csh -x” or “#!/usr/bin/csh -v” Another favourite:“#!/usr/bin/csh -f”Fall 1999CSC209: Software Tools & Systems Programming

Slide 58if Command Syntax:if ( test-expression ) command Example:if ( -w file2 ) mv file1 file2 Syntax:if ( test-expression ) thenshell commandselseshell commandsendifFall 1999CSC209: Software Tools & Systems Programming

Slide 59if Command (cont.) Syntax:if ( test-expression ) thenshell commandselse if ( test-expression ) thenshell commandselseshell commandsendifFall 1999CSC209: Software Tools & Systems Programming

Slide 60foreach Command Syntax:foreach item ( list-of-items )shell commandsend Example:foreach item ( ‘ls *.c’ )cp item /.backup/ itemend Special statements:breakcontinueFall 1999causes control to exit the loopcauses control to transfer to the test at the topCSC209: Software Tools & Systems Programming

Slide 61while Command Syntax:while ( expression )shell commandsend Example:set count 0set limit 7while ( count ! limit )echo “Hello, {USER}”@ count end break and continue have same effects as in foreachFall 1999CSC209: Software Tools & Systems Programming

Slide 62switch Command Syntax:switch ( test-string )case pattern1:shell commandsbreakswcase pattern2:shell commandsbreakswdefault:shell commandsbreakswendFall 1999CSC209: Software Tools & Systems Programming

Slide 63goto Command Syntax:goto label.other shell commands.label:shell commandsFall 1999CSC209: Software Tools & Systems Programming

Slide 64repeat Command Syntax:repeat count command Example:repeat 10 echo “hello”Fall 1999CSC209: Software Tools & Systems Programming

Slide 65Standard Variables 0 N argv[N] * argv # ! ?Fall 1999 calling function name Nth command line argument valuesame as aboveall the command line argumentssame as abovethe number of command line argumentsan input line, read from stdin of the shellprocess number (PID) of the current processprocess number (PID) of the last background processexit status of the last taskCSC209: Software Tools & Systems Programming

Slide 66Other Shell Commandssource fileshiftshift variablerehash Other commands see Wang, Appendix 7Fall 1999CSC209: Software Tools & Systems Programming

Slide 67Example: ls2# Usage: ls2# produces listing that separately lists files and dirsset dirs ls -F grep '/' set files ls -F grep -v '/' echo "Directories:"foreach dir ( dirs)echo " " direndecho "Files:"foreach file ( files)echo " " fileendFall 1999CSC209: Software Tools & Systems Programming

Slide 68Example: components#!/usr/bin/csh -fset test a/b/c.decho "the full string is:" testecho "extension (:e) is: " test:eecho "head (:h) is: " test:hecho "root (:r) is: " test:recho "tail (:t) is: " test:t### output:# the full string is: a/b/c.d# extension (:e) is: d# head (:h) is: a/b# root (:r) is: a/b/c# tail (:t) is: c.dFall 1999CSC209: Software Tools & Systems Programming

Slide 69Example: debug#!/usr/bin/csh -xwhile ( #argv )echo argv[1]shiftend# while ( 2 )# echo a# a# shift# end# while ( 1 )# echo b# b# shift# end# while ( 0 )Fall 1999 output of "debug a b"CSC209: Software Tools & Systems Programming

Slide 70Example: newcopy#!/usr/bin/csh -f### An old exam question:# Write a csh script “newcopy dir ” that copies files# from the directory dir to the current directory.# Only the two most recent files having the name progN.c# are to be copied, however, where N can be any of 1, 2,# 3, or 4. The script can be written in 3 to 5 lines:set currdir cwdcd argv[1]set list ( ls -t -1 prog[1-4].c head -2 awk '{print 8}' )foreach file ( list)cp file currdir/.endFall 1999CSC209: Software Tools & Systems Programming

Section IIISYSTEMSPROGRAMMING

Slide 72Initializing UNIX The first UNIX program to be run is called “/etc/init” It forks and then execs one “/etc/getty” per terminal getty sets up the terminal properly, prompts for a login name, and thenexecs “/bin/login” login prompts for a password, encrypts a constant string using thepassword as the key, and compares the results against the entry in thefile “/etc/passwd” If they match, “/usr/bin/csh” (or whatever is specified in thepasswd file as being that user’s shell) is exec’d When the user exits from their shell, the process dies. Init finds outabout it (wait system call), and forks another process for that terminalFall 1999CSC209: Software Tools & Systems Programming

Slide 73Initializing UNIXinitinitinitinitinitinitgettylogincsh See “top”, “ps -aux”, etc. to see what’s running at any given time The only way to create a new process is to duplicate an existingprocess, therefore the ancestor of ALL processes is init, with pid 1Fall 1999CSC209: Software Tools & Systems Programming

Slide 74How csh runs commands dateSun May 25 23:11:12 EDT 1997 When a command is typed csh forks and then execs the typed command:cshcshcshcshdatecsh After the fork and exec, file descriptors 0, 1, and 2 still refer to thestandard input, output, and error in the new process By UNIX programmer convention, the executed program will use thesedescriptors appropriatelyFall 1999CSC209: Software Tools & Systems Programming

Slide 75How csh runs (cont.)process running shell,PID 34parent process running shell,PID 34, waiting for childduplicate:fork()child process running shell, PID 35differentiate:exec()wait for child:wait()child process running utility, PID 35terminate:exit()parent process running shell,PID 34, awakensFall 1999signalchild process terminates PID 35CSC209: Software Tools & Systems Programming

Slide 76Tools and Applicationsvicatmoredategccgdb csh (or any other shell)UNIX system servicesUNIX kernel in CcomputerFall 1999CSC209: Software Tools & Systems Programming

Slide 77C and libcC Application Programslibc - C Interface to UNIX system servicesUNIX system servicesUNIX kernel in CcomputerFall 1999CSC209: Software Tools & Systems Programming

Slide 78Concurrency Most modern developments in computer systems & applications rely on:– communication: the conveying of info by one entity to another– concurrency: the sharing of resources in the same time framenote: concurrency can exist in a single processor system as well as ina multiprocessor system. Managing concurrency is difficult, as execution behaviour (e.g. relativeorder of execution) is not always reproducible More details on this in the last 1/3 or the courseFall 1999CSC209: Software Tools & Systems Programming

Slide 79Concurrency ExampleProgram a:#!/usr/bin/csh -f@ count 0while( count 200 )@ count echo -n "a"endProgram b:#!/usr/bin/csh -f@ count 0while( count 200 )@ count echo -n "b"end When run sequentially (a;b) output is as expected When run concurrently (a&;b&) output is interspersed, and re-runningit may produce different outputFall 1999CSC209: Software Tools & Systems Programming

Slide 80Race conditions A race condition occurs when multiple processes are trying todo something with shared data and the final outcome dependson the order in which the processes run This is a situation when using forks: if any code after the forkexplicitly or implicitly depends on whether or not the parentor child runs first after the fork A parent process can call wait() for a child to terminate(may block) A child process can wait for the parent to terminate bypolling it (wasteful) Standard solution is to use signalsFall 1999CSC209: Software Tools & Systems Programming

Slide 81Example: Race Condition#!/usr/bin/csh -fset count 0while( count 50 )set sharedData cat shareVal @ sharedData echo sharedData ! shareVal@ count end Create two identical copies, “a” and “b” Run as: ./a&; ./b&Fall 1999CSC209: Software Tools & Systems Programming

Slide 82Producer/Consumer Problem Simple example:who wc -l Both the writing process (who) and the readingprocess (wc) of a pipeline execute concurrently A pipe is usually implemented as an internal OSbuffer It is a resource that is concurrently accessed by thereader and by the writer, so it must be managedcarefullyFall 1999CSC209: Software Tools & Systems Programming

Slide 83Producer/Consumer (cont.) consumer should be blocked when buffer is empty producer should be blocked when buffer is full producer and consumer should run independently so far asthe buffer capacity and contents permit producer and consumer should never both be updating thebuffer at the same instant (otherwise, data integrity cannotbe guaranteed) producer/consumer is a harder problem if there is morethan one consumer and/or more than one producerFall 1999CSC209: Software Tools & Systems Programming

Intro to Systems Programming

Slide 85Using argc & argv Function main() in C programs declared asint main( int argc, char *argv[]) These parameters are passed by the O/S– argc: The number of command-lineparameters plus one– argv: An array of string pointers, eachof which points to one parameterFall 1999CSC209: Software Tools & Systems Programming

Slide 86Example: argc/argv#include stdio.h #include sys/stat.h int main( int argc, char *argv[]){if( argc 2 ){struct stat buf;if( stat( argv[1], &buf ) ! -1 )printf( “file %s has size %d\n”,argv[1], buf.st size );}return( 0 );}Fall 1999CSC209: Software Tools & Systems Programming

Slide 87System Calls System calls:– perform a subroutine call directly to the UNIXkernel 3 main categories:– file management– process management– error handlingFall 1999CSC209: Software Tools & Systems Programming

Slide 88Error Handling All system calls return -1 if an error occurs errno:– global variable that holds the numeric code of the last system call perror(): – a subroutine that describes system call errorsEvery process has errno initialized to zero at process creation timeWhen a system call error occurs, errno is setSee /usr/include/sys/errno.hA successful system call never affects the current value of errno An unsuccessful system call always overwrites the current value oferrnoFall 1999CSC209: Software Tools & Systems Programming

Slide 89perror() Library routine:void perror( char *str ) perror displays str, then a colon (:), then an englishdescription of the last system call error, as defined in theheader file/usr/include/sys/errno.h Protocol:– check system calls for a return value of -1– call perror() for an error description duringdebugging(see example on next slide)Fall 1999CSC209: Software Tools & Systems Programming

Slide 90perror() example#include stdio.h #include errno.h int main( void ){int returnVal;printf( "x2 before the execlp, pid %d\n", getpid());returnVal execlp( "nonexistent file", (char *)0);if( returnVal -1 )perror( "x2 failed" );return( 1 );}Fall 1999CSC209: Software Tools & Systems Programming

Slide 91Fork The fork system call is used to create a duplicate of the currentlyrunning programprocessA #1processAforkprocessA #2 The duplicate (child process) and the original (parent process) bothproceed from the point of the fork with exactly the same data The only difference between the two processes is the fork return value,i.e. ( see next slide)Fall 1999CSC209: Software Tools & Systems Programming

Slide 92Fork exampleint i, pid;i 5;printf( “%d\n”, i );pid fork();if ( pid ! 0 )i 6; /* only the parent gets to here */elsei 4; /* only the child gets

UNIX Network Programming, Richard Stevens. Fall 1999 CSC209: Software Tools & Systems Programming Slide 12 Course Content Why UNIX? History UNIX Basics: Processes, Login Shells: command processing, running programs, shell programming I/O: file descriptors vs. streams

Related Documents:

Pro Tools 9.0 provides a single, unified installer for Pro Tools and Pro Tools HD. Pro Tools 9.0 is supported on the following types of systems: Pro Tools HD These systems include Pro Tools HD software with Pro Tools HD or Pro Tools HD Native hard-ware. Pro Tools These systems include Pro Tools software with 003 or Digi 002 family audio .

Programming paradigms Structured programming: all programs are seen as composed of control structures Object-oriented programming (OOP): Java, C , C#, Python Functional programming: Clojure, Haskell Logic programming based on formal logic: Prolog, Answer set programming (ASP), Datalog

Automation test script is repeatable Proficiency is required to write the automation test scripts. A. Automation Tools Categories Software testing automation tools can be divided into different categories as follows: Unit Testing Tools, Functional Testing Tools, Code Coverage Tools, Test Management Tools, and Performance Testing Tools.

Abstract - A Programming Paradigm is the silent intelligence in any software design. Although many Programming Paradigms have evolved, only a few programming paradigms are actively used by the software industry. In addition, many hundreds of programming languages have been developed, but only a few are established and beneficial.

Legal Information All Software and Computer Systems Company, LLC logos shown in this document are a trademark (TM) of Software and Computer Systems Company, LLC.Scannerz is trademark (TM) of Software and Computer Systems Company, LLC.All software produced and licensed by Software and Computer Systems Company, LLC is copyright Software and Computer Systems Company, LLC 2010 - 2012, The .

The C programming language was developed in the early 1980s. C was designed to add object-oriented programming techniques to the C language. Although C originally tended to be associated with systems programming, it has evolved into a mature programming language that is well-suited for a wide variety of application programming.

Object Oriented Programming 7 Purpose of the CoursePurpose of the Course To introduce several programming paradigms including Object-Oriented Programming, Generic Programming, Design Patterns To show how to use these programming schemes with the C programming language to build “good” programs.

ASME NQA-1–2019 (Revision of ASME NQA-1–2017) Quality Assurance Requirements for Nuclear Facility Applications AN AMERICAN NATIONAL STANDARD x This is a preview of "ASME NQA-1-2019".