32
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

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

Embed Size (px)

Citation preview

Page 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

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

Page 2: 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

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.

Page 3: 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

How a C program is started and terminated.

Page 4: 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

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.

Page 5: 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

Process Termination#include <stdlib.h>void exit(int status); •ANSI C•Perform cleanup processing

• Close and flush I/O streams (fclose)#include <unistd.h>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 <stdio.h>

main() {

printf(“hello world\n”);

}

Page 6: 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

Process Termination

#include <stdlib.h>

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

Page 7: 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

#include "ourhdr.h"static void my_exit1(void), my_exit2(void);intmain(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 voidmy_exit1(void){

printf("first exit handler\n");}static voidmy_exit2(void){

printf("second exit handler\n");}

Program 7.1

Page 8: 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

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

Page 9: 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

#include "ourhdr.h"

intmain(int argc, char *argv[]){

int i;

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 fooargv[0]: ./echoargargv[1]: arg1argv[2]: TESTargv[3]: foo

Page 10: 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

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

Page 11: 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

high addresscommand-linearguments and

environment variables

heap

stack

unititializeddata (bss)

text

Initialized to 0by exec

Read fromprogram file

by exec

ititialized data

low address

Typical memory Layout

Page 12: 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

Memory Layout: size command

• size --reports size in bytes of text, data and bss segments

Example

$ size /bin/cc text data bss dec hex81920 16384 664 98968 18298 /bin/cc

Page 13: 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

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.

Page 14: 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

Memory Allocation#include <stdlib.h>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 <stdio.h>

#include <stdlib.h>

main() {

char *ptr;

ptr = malloc(100);

free(ptr);

free(ptr);

ptr[0] = 'a'; ptr[1]=0;

printf("%s - Done\n", ptr);

}

Page 15: 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

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.

Page 16: 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

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 <stdlib.h>

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.

Page 17: 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

Environment Variables#include <stdlib.h>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.

Page 18: 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

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.

Page 19: 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

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 framesStack status after call to cmd_add

Page 20: 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

#include ‘ourhdr.h’#define TOK_ADD 5void do_line(char *);void cmd_add( void);void get_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 */{

int cmd;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

Page 21: 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

setjmp and longjmp

#include <setjmp.h>

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

Page 22: 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

#include <setjmp.h>#include ‘ourhdr.h’#define TOK_ADD 5jmp_buf jumbuffer; 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 

Page 23: 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

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!

Page 24: 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

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.

Page 25: 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

#include <setjmp.h>#include "ourhdr.h"static void f1(int, int, int);static void f2(void);static jmp_buf jmpbuffer;intmain(void){

int count;register int val;volatile int sum;

  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 voidf1(int i, int j, int k){

printf("in f1(): count = %d, val = %d, sum = %d\n", i, j, k);f2();

}static voidf2(void){

longjmp(jmpbuffer, 1);}  Program 7.5 : Effect of long_jmp on automatic, register and volatile variables

Page 26: 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

Execution example of program 7.5

$ cc testjmp.c compile without optimisation

$ a.out

In f1(): count = 97, val = 98, sum = 99

After long_jmp: count = 97, val = 98, sum = 99

$ cc –O testjmp.c compile with full optimisation

$ a.out

In f1(): count = 97, val = 98, sum = 99

After long_jmp: count = 2, val = 3, sum = 99

Page 27: 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

#include <stdio.h> #define DATAFILE "datafile" FILE *open_data(void){

FILE *fp;char databuf[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

Page 28: 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

getrlimit and setrlimitEvery process has set of resource limits; some of these limits can

be changed using getrlimit anr setrlimit.#include <sys/time.h>#include <sys/resource.h>int getrlimitint resource, struct rlimit *rlptr);int setrlimitint resource, const struct rlimit *rlptr);

both return 0 if OK, nonzero on errorThese 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 */

}

Page 29: 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

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

Page 30: 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

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)

Page 31: 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

#include <sys/types.h>#include <sys/time.h>#include <sys/resource.h>#include "ourhdr.h"#define doit(name) pr_limits(#name, name)static void pr_limits(char *, int);intmain(void){

doit(RLIMIT_CORE);doit(RLIMIT_CPU);doit(RLIMIT_DATA);doit(RLIMIT_FSIZE);

#ifdef RLIMIT_MEMLOCK doit(RLIMIT_MEMLOCK);#endif#ifdef RLIMIT_NOFILE /* SVR4 name */

doit(RLIMIT_NOFILE);#endif#ifdef RLIMIT_OFILE /* 44BSD name */

doit(RLIMIT_OFILE);#endif#ifdef RLIMIT_NPROC

doit(RLIMIT_NPROC);#endif#ifdef RLIMIT_RSS

doit(RLIMIT_RSS);#endif

doit(RLIMIT_STACK);#ifdef RLIMIT_VMEM

doit(RLIMIT_VMEM);#endif

exit(0);}

Page 32: 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

static void

pr_limits(char *name, int resource)

{

struct rlimit limit;

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