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.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Chris Riesbeck, Fall 2007 Dynamic Memory Allocation Today Dynamic memory allocation – mechanisms & policies Memory bugs.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
LINUX System Process (additional slides)
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
1 Memory Allocation Professor Jennifer Rexford COS 217.
User-Level Memory Management in Linux Programming
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
System Files and Process Environment Password file Group file System identification Time Process environment.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction.
[Unix Programming] Process Basic Young-Ju, Han
Memory and Files Dr. Andrew Wallace PhD BEng(hons) EurIng
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
CSCE Systems Programming Lecture 05 - Processors, Memory CSCE 510 Jan 23, 2013.
The Environment of a UNIX Process. Introduction How is main() called? How are arguments passed? Memory layout? Memory allocation? Environment variables.
Process Control Hua LiSystems ProgrammingCS2690Process Control Page 1 of 41.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Process in Unix, Linux and Windows CS-3013 C-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
CS-502 Fall 2006Processes in Unix, Linux, & Windows 1 Processes in Unix, Linux, and Windows CS502 Operating Systems.
Unix Process Environment. main Function A C program starts execution with a function called main. The prototype for the main function is: int main (int.
Unix & Windows Processes 1 CS502 Spring 2006 Unix/Windows Processes.
Advanced Programming in the UNIX Environment Hop Lee.
Processes in Unix, Linux, and Windows CS-502 Fall Processes in Unix, Linux, and Windows CS502 Operating Systems (Slides include materials from Operating.
System Calls 1.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
Process in Unix, Linux, and Windows CS-3013 A-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
Fundamentals CIS 552. Fundamentals Low-level I/O (read/write using system calls)  Opening/Creating files  Reading & Writing files  Moving around in.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
1 Logging in to a UNIX System init ( Process ID 1 created by the kernel at bootstrap ) spawns getty for every terminal device invokes our login shell terminal.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
System calls for Process management
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Processes CS 6560: Operating Systems Design. 2 Von Neuman Model Both text (program) and data reside in memory Execution cycle Fetch instruction Decode.
Operating Systems Process Creation
What is a Process? u A process is an executable “cradle” in which a program may run u This “cradle” provides an environment in which the program can run,
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
Process Management Azzam Mourad COEN 346.
Minimal standard C program int main(void) { return 0 ; }
1 System Programming Chapter 7. 2 Fun Stuff Touch-based Communication.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
System calls for Process management Process creation, termination, waiting.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
Using System Calls (Unix) Have to tell compiler (if C/C++) where to find the headers, etc. – i.e., the “include” files May have to tell compiler where.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Recitation 7 – 3/18/02 Outline fork and scheduling Signals
Stack and Heap Memory Stack resident variables include:
Linux Processes & Threads
Using Processes.
Unix Process Management
Programmazione I a.a. 2017/2018.
Dynamic Memory Allocation
Lecture 5: Process Creation
Unix Process Course code: 10CS62 Prepared by : Department of CSE.
Chapter 14 - Advanced C Topics
Memory Allocation CS 217.
Understanding Program Address Space
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
File Input and Output.
The Environment of Unix Process
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Processes in Unix and Windows
Dynamic Memory – A Review
Presentation transcript:

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

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.

How a C program is started and terminated.

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.

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”); }

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

#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

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

#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

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

Typical memory Layout

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

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.

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); }

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.

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.

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.

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.

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

#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

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

#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

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!

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.

#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

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

#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

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 */ }

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

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)

#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); }

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