Presentation is loading. Please wait.

Presentation is loading. Please wait.

Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files.

Similar presentations


Presentation on theme: "Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files."— Presentation transcript:

1 Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information  7. Environment of a Unix Process 8. Process Control 9. Signals 10.Inter-process Communication

2 The Environment of a Unix Process  Objective: How main function is called when program is executed. How program terminates execution How command-line arguments are passed What the typical memory layout is Alloc memory, use environment variables,…. main function int main(int argc, char *argv[]) -- prototype When program is started by kernel, a special start-up routine is called before calling main(). Start-up routine is set up by the link editor as part of the executable. Start-up routine takes command-line arguments and environment variable to prepares execution of main function.

3 How a C program is started and terminated.

4 Process Termination  Five ways to terminate: Normal termination – Return from main(). exit(main(argc, argv)); – Call exit(). – Call _exit() Abnormal termination – Call abort() – Be terminated by a signal.

5 Process Termination #include void exit(int status); ANSI C Perform cleanup processing Close and flush I/O streams (fclose) #include void _exit(int status); POSIX.1 Undefined exit status: Exit/return without status. Main falls off the end. In the case the termination is a return from main, start-up routine takes the control back and calls exit. #include main() { printf(“hello world\n”); }

6 Process Termination #include int atexit(void (*func)(void)); -- defines exit handlers Up to 32 functions called by exit The same exit handlers can be registered for several times. Exit handlers will be called in reverse order of their registration. Program 7.1: example of usage of exit handlers

7 #include"ourhdr.h" static voidmy_exit1(void), my_exit2(void); int main(void) { if (atexit(my_exit2) != 0) err_sys("can't register my_exit2"); if (atexit(my_exit1) != 0) err_sys("can't register my_exit1"); if (atexit(my_exit1) != 0) err_sys("can't register my_exit1"); printf("main is done\n"); return(0); } static void my_exit1(void) { printf("first exit handler\n"); } static void my_exit2(void) { printf("second exit handler\n"); } Program 7.1

8 Command-Line Arguments & Environment Variables  Command-Line Arguments argv[argc] is NULL under POSIX.1 & ANSI C Program 7.2  Environment Variables int main(int argc, char *argv, char *envp); by convention, env is represented as name=value; null terminated string for env. variables

9 #include"ourhdr.h" int main(int argc, char *argv[]) { inti; for (i = 0; i < argc; i++)/* echo all command-line args */ printf("argv[%d]: %s\n", i, argv[i]); exit(0); } Program 7.2 EXAMPLE: $./echoarg arg1 TEST foo argv[0]:./echoarg argv[1]: arg1 argv[2]: TEST argv[3]: foo

10 Memory Layout Components of a C program  Text Segment Read-only usually, sharable  Initialized Data Segment example. int var1 = 10;  Uninitialized Data Segment – bss (Block Started by Symbol) Initialized to 0 or NULL pointer by exec long sum[1000];  if outside a function, in uninitialized segment  Stack – return addr, automatic var, etc.  Heap – dynamic memory allocation

11 Typical memory Layout

12 Memory Layout: size command size --reports size in bytes of text, data and bss segments Example $ size /bin/cc textdatabssdechex /bin/cc

13 Memory Allocation  Three ANSI C Functions:  malloc – allocate a specified number of bytes of memory. Initial values are indeterminate.  calloc – allocate a specified number of objects of a specified size. The space is initialized to all 0 bits.  realloc – change the size of a previously allocated area. The initial value of increased space is indeterminate.

14 Memory Allocation #include void *malloc(size_t size); void *calloc(size_t nobj, size_t size); void *realloc(void *ptr, size_t newsize);  Suitable alignments for any data obj  Returns generic void * pointer  free(void *ptr) to release space to a pool of free memory.  Leakage problem #include main() { char *ptr; ptr = malloc(100); free(ptr); ptr[0] = 'a'; ptr[1]=0; printf("%s - Done\n", ptr); }

15 Memory Allocation realloc() used to increase or decrease size of previously allocated area. Typical use is to increase size. realloc() could trigger moving of data -> avoid pointers to that area. sbrk() is used to implement memory allocation: expand or contract the heap of a process – a malloc pool Record-keeping info requires reservation of extra space within allocated area  !!!writing beyond end of allocated area will result is the destruction of record-keeping info!!!. be careful to free strictly what has been allocated through malloc!!!! leakage problem: keep calling malloc without calling free. alloca() allocates space from the stack frame of the current function! No needs for free with potential portability problems because of difficulty to handle memory allocation, new version of Unix systems provide additional control and error checking of malloc and free functions. For example, SVR4 provides mallopt(M_GRAINSet, value) to set variables to control operation of memory allocator.

16 Environment Variables  Name=value Interpretation is up to applications. Setup automatically or manually E.g., HOME, USER, PATH, TERM, etc. setenv FONTPATH X11R6HOME/lib/X11/fonts\:$OPENWINHOME/lib/font #include char *getenv(const char *name); returns pointer to value associated with name, NULL if not found. ANSI C function, but no ANSI C environment variable.

17 Environment Variables #include int putenv(const char *name-value); Takes a string name=value and places it in env list; removes old definitions if they exist. int setenv(const char *name, const char *value, int rewrite); returns 0 if OK, nonzero if error sets name to value; if name exists, then a) if rewrite  0, existing name is first removed; b) if rewrite = 0  not removing of existing names, no modif, no error reported. int unsetenv(const char *name); Remove any def of the name No error msg if no such def exists.

18 Environment Variables  Adding/Deleting/Modifying of existing name  Modifying The size of a new value <= the size of the existing value  overwriting Otherwise; malloc() & redirect the ptr  Adding The first time we add a new name  malloc of pointer-list’s room & update environ Otherwise; copying. realloc() if needed.  The heap segment could be involved.

19 setjmp and longjmp  Objective: In C, no goto to a label located in another function: use setjmp ang longjmp useful to handle error cases in a deeply nested function call Example: program 7.3  What if cmd_add() suffers a non fatal error? How to return to main() to get the next line? NEED setjmp ang longjmp Note: Automatic variables are allocated within the stack frames Stack status after call to cmd_add

20 #include ‘ourhdr.h’ #define TOK_ADD5 voiddo_line(char *); voidcmd_add( void); voidget_token( void); int main(void) { char line(MAXLINE) ; while (fgets(line, MAXLINE, stdin) !=NULL) do_line(line); exit(0); } char *tok_ptr; /* global pointer for get_token() */ void do_line(char *ptr)/* process one line of input */ { intcmd; tok_ptr = ptr; while ( ( cmd=get_token())>0 ) { switch(cmd) {/* one case for each command */ case TOK_ADD; cmd_add(); break }; } void cmd_add(void) { int token; token=get_token(); /* rest of processing for this command */ } int get_token(void) { /* fetch next token from line pointed to by tok_ptr */ } Program 7.3: Typical program skeleton for command processing

21 setjmp and longjmp #include int setjmp(jmp_buf env); int longjmp(jmp_buf env, int val); Return 0 if called directly; otherwise, it could return a value val from longjmp(). env tends to be a global variable. longjmp() unwinds the stack and affect some variables.  Program 7.4 setjmp and longjmp

22 #include #include ‘ourhdr.h’ #define TOK_ADD5 jmp_bufjumbuffer; int main(void) { char line(MAXLINE) ; if (set_jmp(jmpbuffer)!=0) printf(“error”); /* return point */ while (fgets(line, MAXLINE, stdin) !=NULL) do_line(line); exit(0); } ………………. void cmd_add(void) { int token; token=get_token(); if (token<0) /* an error occurred */ long_jmp(jmpbuffer,1); /* rest of processing for this command */ } Program 7.4: Example of set_jmp and long_jmp

23 setjmp and longjmp  What are the values of Automatic, Register, and Volatile Variables in main function after return from long_jmp?  Compiler optimization Register variables could be in memory.  Values are often indeterminate Normally no roll back on automatic and register variables As shown in Program 7.5 Global and static variables are left alone when longjmp is executed.  Portability Issues!

24 setjmp and longjmp  Program 7.5 Effects of longjmp Variables stored in memory have their values unchanged – no optimization …  Potential Problems with Automatic Variables – Program 7.6 Never be referenced after their stack frames are released.

25 #include #include"ourhdr.h" static voidf1(int, int, int); static voidf2(void); static jmp_bufjmpbuffer; int main(void) { intcount; register intval; volatile intsum; count = 2; val = 3; sum = 4; if (setjmp(jmpbuffer) != 0) { printf("after longjmp: count = %d, val = %d, sum = %d\n", count, val, sum); exit(0); } count = 97; val = 98; sum = 99; /* changed after setjmp, before longjmp */ f1(count, val, sum);/* never returns */ } static void f1(int i, int j, int k) { printf("in f1(): count = %d, val = %d, sum = %d\n", i, j, k); f2(); } static void f2(void) { longjmp(jmpbuffer, 1); } Program 7.5 : Effect of long_jmp on automatic, register and volatile variables

26 Execution example of program 7.5 $ cc testjmp.ccompile without optimisation $ a.out In f1(): count = 97, val = 98, sum = 99 After long_jmp: count = 97, val = 98, sum = 99 $ cc –O testjmp.ccompile with full optimisation $ a.out In f1(): count = 97, val = 98, sum = 99 After long_jmp: count = 2, val = 3, sum = 99

27 #include #defineDATAFILE"datafile" FILE * open_data(void) { FILE*fp; chardatabuf[BUFSIZ]; /* setvbuf makes this the stdio buffer */ if ( (fp = fopen(DATAFILE, "r")) == NULL) return(NULL); if (setvbuf(fp, databuf, BUFSIZ, _IOLBF) != 0) return(NULL); return(fp);/* error */ } Program 7.6: Incorrect usage of an automatic variable

28 getrlimit and setrlimit Every process has set of resource limits; some of these limits can be changed using getrlimit anr setrlimit. # include int getrlimitint resource, struct rlimit *rlptr); int setrlimitint resource, const struct rlimit *rlptr); both return 0 if OK, nonzero on error These functions specify a single resource and a pointer to following structure:  Not POSIX.1, but supported by SVR4 and 4.4BSD  Rules: Any process can change its soft limit to a value <= hard limit Any process can lower its hard limit to a value <= soft limit; the lowering of hard limits is irreversible. Only a super-user can raise a hard limit. struct rlimit { rlim_t rlim_cur; /* soft limit */ rlim_t rlim_max; /* hard limit */ }

29 getrlimit and setrlimit  Most important resources arguments RLIMIT_CORE: max size in bytes of a core file. 0: no creation of core file RLIMIT_CPU: max CPU time in seconds. When soft limit exceeded, SIGXCPU generated RLIMIT_DATA: max size in bytes of data segment. Represents sum of initialized data, un-initialized data, and heap RLIMIT_FSIZE: max size in bytes of a created file. When soft limit exceeded, SIGXFSZ generated RLIMIT_NOFILE: max number of open files per process.Changes of this limit affect _SC_OPEN_MAX value returned by sysconf RLIMIT_NPROC: max number of child processes per real user ID. Changes of this limit affect _SC_CHILD_MAX value returned by sysconf RLIMIT_STACK: max size of stack

30 getrlimit and setrlimit  Resource Limits: inheritance by processes Built-in commands in shells umask, chdir, limit (C shall), ulimit –H and –S (Bourne shell and KornShell)  Program 7.7 Print out current soft and hard process resource limits, under current Operating System. Need conditional compilation #define RLIM_NLIMITS 7 doit(RLIMIT_CORE) = pr_limits(“RLIMIT_CORE”, RLIMIT_CORE) #define doit(name) pr_limits(#name, name)

31 #include #include"ourhdr.h" #definedoit(name)pr_limits(#name, name) static voidpr_limits(char *, int); int main(void) { doit(RLIMIT_CORE); doit(RLIMIT_CPU); doit(RLIMIT_DATA); doit(RLIMIT_FSIZE); #ifdefRLIMIT_MEMLOCK doit(RLIMIT_MEMLOCK); #endif #ifdefRLIMIT_NOFILE/* SVR4 name */ doit(RLIMIT_NOFILE); #endif #ifdefRLIMIT_OFILE/* 44BSD name */ doit(RLIMIT_OFILE); #endif #ifdefRLIMIT_NPROC doit(RLIMIT_NPROC); #endif #ifdefRLIMIT_RSS doit(RLIMIT_RSS); #endif doit(RLIMIT_STACK); #ifdefRLIMIT_VMEM doit(RLIMIT_VMEM); #endif exit(0); }

32 static void pr_limits(char *name, int resource) { struct rlimitlimit; if (getrlimit(resource, &limit) < 0) err_sys("getrlimit error for %s", name); printf("%-14s ", name); if (limit.rlim_cur == RLIM_INFINITY) printf("(infinite) "); else printf("%10ld ", limit.rlim_cur); if (limit.rlim_max == RLIM_INFINITY) printf("(infinite)\n"); else printf("%10ld\n", limit.rlim_max); } Program 7.7: Print current resource limits


Download ppt "Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files."

Similar presentations


Ads by Google