Unformatted text preview:

C ProgramsC Header FilesProcessVariable LifetimesThreadsMultiple ThreadsActivation RecordFunction Errorsclose Exampleperrorclose Example with perrorperror Exampleerrnoperror/errno Examplestrerrorstrerror ExampleSuggestionsargv array for mine –c 10 2.0makeargv, first halfmakeargv, second halfargtestmakeargv data structuresstrtokThread Safe FunctionsShow HistoryAsync-Signal Safe FunctionsreadSolutions to read Problemexit, _Exit, _exit Synopsisatexit SynopsisC Programs• Preprocessor commands–#ifdef– #include– #define• Type and macro definitions• Variable and function declarations• Exactly one main function• Function calls and other executable statements• Have a .c extensionC Header Files• Have a .h extension• Usually contain only :–macro– type definitions– defined constants– function declarations• Include header files with the #include preprocessor commandProcess• Instance of a program in execution• Each instance has its own address space and execution state• Has a process ID and a state• The OS manages memory allocated to the process• Process has a flow of control called a thread• Heavyweight processVariable Lifetimes• Process variables that remain in effect for the lifetime of the process are allocated to static storage• Process variables that are automatically created when execution enters a block and are destroyed when execution leaves the block are allocated to automatic storageThreads• When a program executes, the pc determines which process instruction is executed next• The resulting stream of instructions are called a thread of executionMultiple Threads• A natural extension is to have multiple threads within the same process• Each thread can be an independent task to complete the process executed in parallel• Each thread is an abstract data type that has its own:– execution stack– pc value– register set– state• Threads have low overhead and are frequently called lightweight processes.Program LayoutProgram textInitialized static dataUn-initialized static dataStack↓↑HeapCommand Line Arguments and Environment VariablesÅ argc, argv, environmentÅ Activation records for function calls (return address, parameters, savedregisters, automatic variables)Å allocations from malloc familyActivation Record• Allocated at top of process stack• Holds execution context (data) of a function call• Removed from stack at end of function call• Contains:– return address– stack management information– parameters– automatic variablesStatic Variable Example•Version 1:• int myarray[5000] = {1,2,3,4};• void main(int argc, char *argv[]) • { myarray[0] = 3; }•Version 2:• int myarray[5000];• void main(int argc, char *argv[]) • { myarray[0] = 3; •Do an ls –l after compiling both versions. If integer is 4 bytes, version 1 executable is roughly 20,000 bytes larger.Static Variables and Thread Safe• Static variables can make a program unsafe for threaded execution.• Readdir uses a static variable to hold return values.• This strategy is also used for client/server stubs when marshaling/un-marshaling arguments for remote procedure calls.• Therefore, avoid static variables in a threaded environment wherever possible.Safe Functions• Thread-Safe – Can be invoked concurrently or by multiple threads.• Async-Signal-Safe – Can be called without restriction from a signal handler.These terms replace the older notion of reentrant function.Function Errors• Many functions return –1 on error and set external parameter errno to appropriate error code• Include errno.h in order to access the symbolic names associated with errno• Use errno only immediately after an error is generatedclose ExampleSYNOPSIS#include <unistd.h>int close(int filedes);POSIXReturns 0 if successful or –1 if unsuccessful and sets errnofildes is not validclose was interrupted by a signalEBADFEINTRcauseerrnoperror• Outputs message string to standard error followed by the error message from the last system or library call that produced an error• Place perror immediatelyafter the occurrence of an error SYNOPSIS#include<stdio.h>void perror(const char *s)POSIX:CXclose Example with perror#include <unistd.h>int filedes;if (close(filedes) == –1)perror (“Failed to close the file”);perror Example#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int fd;void main(void){int fd;if ((fd = open("my.file", O_RDONLY)) == -1)perror("Unsuccessful open of my.file");}errno• Test errno only if a function call returns an error• errno can be set to various values depending on the function it is used with• For example, when used with the function open, the value EAGAIN indicates the file is lockedperror/errno Example#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>int fd;void main(void){int fd;while (((fd = open("my.file", O_RDONLY)) == -1) && (errno == EAGAIN));if (fd == -1)perror("Unsuccessful open of my.file");}strerror• Use strerror instead of perror to format a message that contains variable values• The message output depends on the value of errnostrerror Example#include …void main(int argc, char *argv[]){int fd;if ((fd = open(argv[1], O_RDONLY)) == -1)fprintf(stderr, "Could not open file %s: %s\n",argv[1], strerror(errno));}Suggestions• Make use of return values• Do not exit early from functions – use error value from function instead• Make functions general but usable (conflict?)• Do not assume buffer sizes• Use standard system defined limits rather than arbitrary constants• Don’t re-invent the wheel• Don’t modify input parameters unless necessary• Don’t use static (global) variables if automatic (local) variables will do just as well• Be sure to free memory allocated by malloc• Consider recursive calls to functions• Analyze consequences of interrupts• Careful plan the termination of each program componentargv array for mine –c 10 2.0NULL[4][3][2][1][0]Argv[]‘/0’‘e’‘n’‘i’‘m’‘/0’‘c’‘-’‘/0’‘0’‘1’‘/0’‘0’‘.’‘2’makeargv, first half#include …/** Make argv array (*arvp) for tokens in s which are separated by* delimiters. Return -1 on error or the number of tokens otherwise.*/int makeargv(char *s, char *delimiters, char ***argvp){ char *t;char *snew;int numtokens;int i;/* snew is real start of string after skipping leading delimiters */snew = s +


View Full Document

Chico CSCI 372 - C Programs

Download C Programs
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view C Programs and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view C Programs 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?