Unix System Programming - Chapter 2, part a Neal Nelson The Evergreen State College Mar 23, 2010
USP Chapter 2.1 to 2.6 Processes and Threads Program Storage and Linkage Library Function Calls Error Handling Robbins Rules for Functions Argument Arrays Assignment for Week 1, part a, makeargv function
Processes and Threads Process State of Execution Address Space Resources (open files, etc). Thread State of Execution (including stack) Threads of a Process Share address space (stacks not shared) Share resources Need explicit synchronization and mutual exclusion
Threads in USP Here s where threads show up in USP POSIX pthreads in Chapter 12 Signal handlers We want thread-safe code when threads are possible
Program Image Program Image CommandLineArgs EnironmentVariables Stack highaddress Heap UninitializedStaticData InitializedStaticData ProgramText lowaddress
Program Image Initialized Static Data - saved and loaded with program text i n t myarray [ 5 0 0 0 0 ] = { 1, 2, 3, 4 } ; i n t main ( void ) { myarray [ 0 ] = 3 ; return 0 ; } Uninitialized Static Data - allocated upon load i n t myarray [ 5 0 0 0 0 ] ; i n t main ( void ) { myarray [ 0 ] = 3 ; return 0 ; } The first program image on disk is 200,000 bytes larger with initialized static data
Storage Classes in C - Object Lifetimes allocated - programmer controlled malloc and free allocated in heap space static - duration of program Variables declared outside of blocks With or without the static keyword! automatic - duration of activation record Variables declared within blocks Includes value parameters and stack return values Pointers may be automatic, but what they point to usually isn t
Linkage Classes in C - Visibility Rules external linkage Public Globally shared with other files internal linkage Private to file Shared within file no linkage Private (local) to block Not shared
The static keyword and its dual meaning static keyword can 1. Change storage class (object lifetime) 2. Change linkage class (visibility) static on block-local variables changes lifetime to program static on outside-block variables changes visibility to file private static on functions changes visibility to file private
Storage and Linkage Summary (USP Apx A.5 p814) Object declared outside block 1. storage class is static 2. static keyword changes linkage class Object declared inside block 1. Linkage class is none 2. static keyword changes storage class
Static Storage Class and Threads We want thread-safe code Static storage objects are not thread-safe You must enforce mutual exclusion using concurrency tools Use Locks, critical regions, semaphores, etc.
Signal Handler Variables We worry in USP about thread-safe code even without explicit threads Signal handlers are concurrent threads possible in all programs Only local variables (automatic storage class) are intrinsically safe Non-local variables are not safe Allocated storage class (programmer allocated by malloc/free). Static storage class Carefully analyze all non-local variables for thread safety
Using Library Function Calls Man pages are in the book for convenience (Apx A.1) Always consult the man pages on your system Use man -k blah to search man pages Man pages tell you the include files you need Include files are not shown in the listings in this presentation Look ahead to the USP POSIX threads Chapter 12 pp431-432 for important notes about thread safety of lib calls
Library Function Call Errors You must always check and handle error returns from library calls Traditional Unix 1 on return indicates error (sometimes Null). Traditional Unix sets global variable errno (USP p432) Traditional Unix errno may not be thread-safe (consult man errno and again USP pp432) New POSIX library functions return an error number. There is an error string associated with each errno Names for error numbers are given in man errno errno is wiped out by the very next error.
Handling library function errors with perror Don t forget the proper include files There s a string associated with each errno that perror uses i n t f i l d e s ; i f ( c l o s e ( f i l d e s ) == 1) p e r r o r ( F a i l e d to c l o s e the f i l e ) ; Returns, eg, F a i l e d to c l o s e the f i l e : i n v a l i d f i l e d e s c r i p t o after the colon is the errno string
Handling library function errors with strerror strerror returns the errno string more elaborate error messages can be printed function calls like strerror and other lib calls (or your own functions) can wipe out errno i n t f i l d e s ; i f ( c l o s e ( f i l d e s ) == 1) { e r r o r = e r r n o ; / s a v e e r r n o p r i v a t e l y / f p r i n t f ( s t d e r r, F a i l e d to c l o s e f i l e d e s c r i p t o r %d : %s \n, f i l d e s, s t r e r r o r ( e r r n o ) ) ; e r r n o = e r r o r ; / r e s t o r e e r r n o / }
Signal interrupts and library function errors Signal interrupts can cause library EINTR errno, but they aren t really errors Sample code for library call restart on USP p29 Uses while loop until no error, or an error other than EINTR The book provides a restart library for convenience, r close
USP error handling guidelines (p29 bottom) All your functions must check and handle library call errors Functions should not exit on their own (except main) Return errors to caller (ie, propogate errors to caller) Don t change process state outside your function, eg, if you block signals, then unblock them. Release all resources that you allocate, eg, if you malloc, then you free Be sure you release resources at all error returns as well as normal returns.
Robbins rules for writing functions Make a checklist of the guidelines for writing functions in Robbins and Robbins USP pp30-31. Check off each of the guideline items for each of your functions.
A few Robbins rules we haven t mentioned Do not make unnecessary assumptions about sizes of buffers. (This is often hard to implement.) When it is necessary to use limits, use standard system-defined limits rather than arbitrary constants. Do not modify input parameter values unless it makes sense to do so. Do not use static variables or dynamic memory allocation if automatic allocation will do just as well. Consider whether a function is ever called recursively or from a signal handler or from a thread. Functions with variables of static storage class may not behave in the desired way. (The error number can cause a big problem here.) Analyze the consequences of interruption by signals. Carefully consider how the entire program terminates.
Argument Arrays Some sample makeargv code Textbook makeargv code (USP p37) Sherri s makeargv code Neal s makeargv code Your makeargv code Assignment 1, part a, makeargv function 1. Analyze your makeargv code from fall quarter against the Robbins checklist. Analyze Neal s if you can t find yours. Specifically list which numbered items in the checklist are violated. 2. Choose one of the makeargv functions and modify it to work with USP Program 2.1 p34. 3. Assignment details listed on the USP assignments page.