Advanced Uses of Pointers

Slides:



Advertisements
Similar presentations
1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
Advertisements

ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
Process Control Hua LiSystems ProgrammingCS2690Process Control Page 1 of 41.
Processes CSCI 444/544 Operating Systems Fall 2008.
CS 311 – Lecture 14 Outline Process management system calls Introduction System calls  fork()  getpid()  getppid()  wait()  exit() Orphan process.
CS Lecture 15 Outline Process Management System calls – exec() – chdir() – system() – nice() – Accessing User and Group IDs – Redirection Lecture.
Process Control in Unix Operating Systems Hebrew University Spring 2004.
Process in Unix, Linux and Windows CS-3013 C-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
Processes in Unix, Linux, and Windows CS-502 Fall Processes in Unix, Linux, and Windows CS502 Operating Systems (Slides include materials from Operating.
Process. Process Concept Process – a program in execution Textbook uses the terms job and process almost interchangeably A process includes: – program.
Process in Unix, Linux, and Windows CS-3013 A-term Processes in Unix, Linux, and Windows CS-3013 Operating Systems (Slides include materials from.
Lecture 5 Process, Thread and Task September 22, 2015 Kyu Ho Park.
Creating and Executing Processes
ITEC 502 컴퓨터 시스템 및 실습 Chapter 2-1: Process Mi-Jung Choi DPNM Lab. Dept. of CSE, POSTECH.
Process Control Process identifiers Process creation fork and vfork wait and waitpid Race conditions exec functions system function.
Chapter 11 Process Management
Scis.regis.edu ● CS 468: Advanced UNIX Class 5 Dr. Jesús Borrego Regis University 1.
Linux Processes Travis Willey Jeff Mihalik. What is a process? A process is a program in execution A process includes: –program counter –stack –data section.
Process Management CS3320 Spring Process A process is an instance of a running program. –Not the same as “program” or “processor” Process provides.
Operating Systems Process Creation
CS4315A. Berrached:CMS:UHD1 Process Management Chapter 6.
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,
ECE Application Programming
Process Management Azzam Mourad COEN 346.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
1 Unix system calls fork( ) wait( ) exit( ). 2 How To Create New Processes? n Underlying mechanism -A process runs fork to create a child process -Parent.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
S ALVATORE DI G IROLAMO (TA) Networks and Operating Systems: Exercise Session 1.
Linux/UNIX Programming APUE (Process Control) 문양세 강원대학교 IT 대학 컴퓨터과학전공.
A process is a program in execution A running system consists of multiple processes – OS processes Processes started by the OS to do “system things” –
CSE 220 – C Programming malloc, calloc, realloc.
Using Processes.
Unix Process Management
Chapter 3: Processes.
Processes in Unix, Linux, and Windows
UNIX PROCESSES.
Example questions… Can a shell kill itself? Can a shell within a shell kill the parent shell? What happens to background processes when you exit from.
Tarek Abdelzaher Vikram Adve Marco Caccamo
System Structure and Process Model
System Structure and Process Model
Processes in Unix, Linux, and Windows
Lecture 5: Process Creation
System Structure B. Ramamurthy.
LINUX System Programming with Processes (additional)
Processes in Unix, Linux, and Windows
System Structure and Process Model
Operating Systems Lecture 6.
Memory Allocation CS 217.
Process & its States Lecture 5.
Process Creation Process Termination
제11장 프로세스 관리.
EECE.2160 ECE Application Programming
Process Programming Interface
Processes Prof. Ikjun Yeom TA – Mugyo
The Environment of Unix Process
CS 105 “Tour of the Black Holes of Computing!”
Process Control B.Ramamurthy 2/22/2019 B.Ramamurthy.
CS 105 “Tour of the Black Holes of Computing!”
EECE.2160 ECE Application Programming
CSE 451: Operating Systems Winter 2003 Lecture 4 Processes
Unix Process Control B.Ramamurthy 4/11/2019 B.Ramamurthy.
Processes in Unix, Linux, and Windows
Processes in Unix and Windows
CS510 Operating System Foundations
CSE 451: Operating Systems Autumn 2004 Module 4 Processes
Process Description and Control in Unix
Process Description and Control in Unix
Dynamic Memory – A Review
Presentation transcript:

Advanced Uses of Pointers Chapter 17 Advanced Uses of Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved.

Dynamic Storage Allocation C’s data structures, including arrays, are normally fixed in size. Fixed-size data structures can be a problem, since we’re forced to choose their sizes when writing a program. Fortunately, C supports dynamic storage allocation: the ability to allocate storage during program execution. Using dynamic storage allocation, we can design data structures that grow (and shrink) as needed. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Memory Allocation Functions Dynamic storage allocation is used most often for strings, arrays, and structures. The <stdlib.h> header declares three memory allocation functions: malloc—Allocates a block of memory but doesn’t initialize it. calloc—Allocates a block of memory and clears it. realloc—Resizes a previously allocated block of memory. These functions return a value of type void * (a “generic” pointer). Copyright © 2008 W. W. Norton & Company. All rights reserved.

Null Pointers An example of testing malloc’s return value: p = malloc(10000); if (p == NULL) { /* allocation failed; take appropriate action */ } NULL is a macro (defined in various library headers) that represents the null pointer. Some programmers combine the call of malloc with the NULL test: if ((p = malloc(10000)) == NULL) { Copyright © 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Memory for a String Prototype for the malloc function: void *malloc(size_t size); malloc allocates a block of size bytes and returns a pointer to it. size_t is an unsigned integer type defined in the library. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Memory for a String A call of malloc that allocates memory for a string of n characters: p = malloc(n + 1); p is a char * variable. Each character requires one byte of memory; adding 1 to n leaves room for the null character. Some programmers prefer to cast malloc’s return value, although the cast is not required: p = (char *) malloc(n + 1); Copyright © 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Memory for a String Calling strcpy is one way to initialize this array: strcpy(p, "abc"); The first four characters in the array will now be a, b, c, and \0: Copyright © 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Storage for an Array Suppose a program needs an array of n integers, where n is computed during program execution. We’ll first declare a pointer variable: int *a; Once the value of n is known, the program can call malloc to allocate space for the array: a = malloc(n * sizeof(int)); Always use the sizeof operator to calculate the amount of space required for each element. Copyright © 2008 W. W. Norton & Company. All rights reserved.

The calloc Function The calloc function is an alternative to malloc. Prototype for calloc: void *calloc(size_t nmemb, size_t size); Properties of calloc: Allocates space for an array with nmemb elements, each of which is size bytes long. Returns a null pointer if the requested space isn’t available. Initializes allocated memory by setting all bits to 0. Copyright © 2008 W. W. Norton & Company. All rights reserved.

The calloc Function A call of calloc that allocates space for an array of n integers: a = calloc(n, sizeof(int)); By calling calloc with 1 as its first argument, we can allocate space for a data item of any type: struct point { int x, y; } *p; p = calloc(1, sizeof(struct point)); Copyright © 2008 W. W. Norton & Company. All rights reserved.

The realloc Function The realloc function can resize a dynamically allocated array. Prototype for realloc: void *realloc(void *ptr, size_t size); ptr must point to a memory block obtained by a previous call of malloc, calloc, or realloc. size represents the new size of the block, which may be larger or smaller than the original size. Copyright © 2008 W. W. Norton & Company. All rights reserved.

The realloc Function Properties of realloc: When it expands a memory block, realloc doesn’t initialize the bytes that are added to the block. If realloc can’t enlarge the memory block as requested, it returns a null pointer; the data in the old memory block is unchanged. If realloc is called with a null pointer as its first argument, it behaves like malloc. If realloc is called with 0 as its second argument, it frees the memory block. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Deallocating Storage malloc and the other memory allocation functions obtain memory blocks from a storage pool known as the heap. Calling these functions too often—or asking them for large blocks of memory—can exhaust the heap, causing the functions to return a null pointer. To make matters worse, a program may allocate blocks of memory and then lose track of them, thereby wasting space. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Deallocating Storage Example: p = malloc(…); q = malloc(…); p = q; A snapshot after the first two statements have been executed: Copyright © 2008 W. W. Norton & Company. All rights reserved.

Deallocating Storage After q is assigned to p, both variables now point to the second memory block: There are no pointers to the first block, so we’ll never be able to use it again. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Deallocating Storage A block of memory that’s no longer accessible to a program is said to be garbage. A program that leaves garbage behind has a memory leak. Some languages provide a garbage collector that automatically locates and recycles garbage, but C doesn’t. Instead, each C program is responsible for recycling its own garbage by calling the free function to release unneeded memory. Copyright © 2008 W. W. Norton & Company. All rights reserved.

Process Management

Process A process is an instance of a running program. Not the same as “program” or “processor” Process provides each program with two key abstractions: Logical control flow Each program seems to have exclusive use of the CPU. Private address space Each program seems to have exclusive use of main memory. How are these Illusions maintained? Process executions interleaved (multitasking) Address spaces managed by virtual memory system

Process Control Special Processes PID 0 – Swapper (i.e., the scheduler) Kernel process No program on disks correspond to this process PID 1 – init responsible for bringing up a Unix system after the kernel is started User process with superuser privileges Initializing system processes, e.g., various daemons, login processes, etc. /etc/rc* & init or /sbin/rc* & init PID 2 - pagedaemon responsible for paging

A Tree of Processes on a Typical Solaris

Init Process When UNIX starts (boots), there is only one process, called init, with process ID = 1. The only way to create a new process is to duplicate an existing process So init is the ancestor of all subsequent processes. Initially, init duplicates (forks) several times and each child process replaces its code (execs) with the code of the executable “getty” which is responsible for user logins. 2019/2/16 cs3320 22

UNIX process-oriented system calls Name Function fork duplicates a process getpid obtains a process’ ID number getppid obtains a parent process’ ID number exit terminates a process wait waits for a child process exec replaces the code, data, and stack of a process

Process Control Block (PCB) Information associated with each process Process state Program counter CPU registers CPU scheduling information Memory-management information Accounting information I/O status information

Process States

Process Creation & Termination

What’s a Fork() Parent Child fork() if ((pid=fork() == 0){ { … } else { exit(0); If ((pid=fork()) == 0){ { … } else { exit(0); fork() Child is an exact copy of the parent process. They have their own memory space.

fork pid_t fork(void); #include <sys/types.h> #include <unistd.h> pid_t fork(void); The only way beside the bootstrap process to create a new process. Call once but return twice 0 for the child process Child pid for the parent Cannot predict which process runs first Process scheduling Run the same code concurrently, but have completely separate stack and data space

Example Program with getpid() #include <stdio.h> main () { int pid; printf ("I'm the original process with PID %d and PPID %d.\n", getpid (), getppid ()); pid = fork (); /* Duplicate. Child & parent continue from here */ if (pid != 0) /* pid is non-zero, so I must be the parent */ { printf ("I'm the parent process with PID %d and PPID %d.\n",getpid (), getppid ()); printf ("My child's PID is %d\n", pid); }else /* pid is zero, so I must be the child */ { printf ("I'm the child process with PID %d and PPID %d.\n",getpid (), getppid ()); } printf ("PID %d terminates.\n", getpid () ); /* Both processes execute this */ 2019/2/16 cs3320 29

Example Program with getpid() $ myfork I'm the original process with PID 639 and PPID 416. I'm the parent process with PID 639 and PPID 416. My child's PID is 640 PID 639 terminates. I'm the child process with PID 640 and PPID 1. PID 640 terminates. $ 2019/2/16 cs3320 30

fork Normal cases in fork: Inherited properties: The parent waits for the child to complete. The parent and child each go their own way (e.g., network servers). Inherited properties: Real/effective [ug]id, supplementary gid, process group ID, session ID, controlling terminal, set[ug]id flag, current working dir, root dir, file-mode creation mask, signal mask & dispositions, FD_CLOEXEC flags, environment, attached shared memory segments, resource limits Differences on properties: Returned value from fork, process ID, parent pid, tms_[us]time, tms_c[us]time, file locks, pending alarms, pending signals

fork Reasons for fork to fail Usages of fork Too many processes in the system The total number of processes for the real uid exceeds the limit CHILD_MAX Usages of fork Duplicate a process to run different sections of code Network servers Want to run a different program shells (spawn = fork+exec)

Orphan Processes If a parent process terminates before its child terminates, the child process is automatically adopted by the init process The following program shows this. 2019/2/16 cs3320 33

Example Program of Orphan #include <stdio.h> main () { int pid; printf ("I'm the original process with PID %d and PPID %d.\n", getpid (), getppid ()); pid = fork (); /* Duplicate. Child & parent continue from here */ if (pid != 0) /* Branch based on return value from fork () */ { /* pid is non-zero, so I must be the parent */ printf ("I'm the parent process with PID %d and PPID %d.\n", getpid (), getppid ()); printf ("My child's PID is %d\n", pid); }else { /* pid is zero, so I must be the child */ sleep (5); /* Make sure that the parent terminates first */ printf ("I'm the child process with PID %d and PPID %d.\n", getpid (), getppid ()); } printf ("PID %d terminates.\n", getpid () ); /* Both processes execute this */ 34

Example Program of Orphan I'm the original process with PID 680 and PPID 416. I'm the parent process with PID 680 and PPID 416. My child's PID is 681 PID 680 terminates. $ I'm the child process with PID 681 and PPID 1. PID 681 terminates. 2019/2/16 cs3320 35

Example of exit() % cat myexit.c #include <stdio.h> #include <stdlib.h> /* needed for exit */ main() { printf("I am going to exit with status code 42\n"); exit(42); } % myexit I am going to exit with status code 42 % echo status is $? 42 2019/2/16 cs3320 36

Zombie Processes A process cannot leave the system until parent process accepts its termination code even if it has exit-ed If parent process is dead; init adopts process and accepts code If the parent process is alive but is unwilling to accept the child's termination code because it never executes wait() the child process will remain a zombie process. 2019/2/16 cs3320 37

Zombie Processes Zombie processes do not take up system resources But do use up an entry in the system's fixed-size process table Too many zombie processes is a problem 2019/2/16 cs3320 38

Zombie Example #include <stdio.h> main () { int pid; pid = fork (); /* Duplicate */ /* Branch based on return value from fork () */ if (pid != 0) { /* Never terminate, never execute a wait () */ while (1) sleep (1000); }else { exit (42); /* Exit with a silly number */ } 2019/2/16 cs3320 39

Zombie Example $ zombie & [1] 684 $ ps 684 p4 S 0:00 zombie 685 p4 Z 0:00 (zombie <zombie>) 686 p4 R 0:00 ps $ kill 684 [1]+ Terminated zombie 688 p4 R 0:00 ps $ 2019/2/16 cs3320 40

Waiting for a Child: wait() pid_t wait(int *status) Causes a process to suspend until one of its child processes terminates. A successful call to wait() returns the PID of the child process that terminated places a status code into status 2019/2/16 cs3320 41

Waiting for a Child: wait() If a process executes a wait() and has no children, wait() returns immediately with a value of -1 If a process executes a wait(), And one or more children are already zombies, Then wait() returns immediately with the status of one of the zombies 2019/2/16 cs3320 42

Example Program using wait() #include <stdio.h> main () { int pid, status, childPid; printf ("I'm the parent process and my PID is %d\n", getpid()); pid = fork (); /* Duplicate */ if (pid != 0) /* Branch based on return value from fork () */ { printf ("I'm the parent process with PID %d and PPID %d\n",getpid (), getppid ()); /* Wait for a child to terminate. */ childPid = wait (&status); printf("A child with PID %d terminated with exit code %d\n",childPid, status >> 8); }else { printf ("I'm the child process with PID %d and PPID %d\n",getpid (), getppid ()); exit (42); /* Exit with a silly number */ } printf ("PID %d terminates\n", getpid () );

Example Program using wait() $ mywait I'm the parent process and my PID is 695 I'm the parent process with PID 695 and PPID 418 I'm the child process with PID 696 and PPID 695 A child with PID 696 terminated with exit code 42 PID 695 terminates 2019/2/16 cs3320 44

Differentiating a Process: exec With the exec family, a process replaces Its current code Data Stack PID and PPID stay the same Only the code that the process is executing changes 2019/2/16 cs3320 45

Differentiating a Process: exec Use the absolute or relative name int execl(const char* path, const char* arg0, ..., const char* argn, NULL) int execv(const char* path, const char* argv[ ]) 2019/2/16 cs3320 46

Differentiating a Process: exec Use $PATH variable to find the executable: int execlp(const char* path, const char* arg0, ..., const char* argn, NULL) int execvp(const char* path, const char* argv[ ]) 2019/2/16 cs3320 47

Differentiating a Process: exec argi or argv[i]: ith command line argument for executable (arg0: name of executable) If executable is not found, -1 is returned otherwise the calling process replaces its code, data, and stack with those of the executable and starts executing the new code A successful exec() never returns 2019/2/16 cs3320 48

Example Using execl() #include <stdio.h> #include <unistd.h> main () { printf ("I'm process %d and I'm about to exec an ls -l\n", getpid ()); execl ("/bin/ls", "ls", "-l", NULL); /* Execute ls */ printf ("This line should never be executed\n"); } $ myexec I'm process 710 and I'm about to exec an ls -l total 38 -rw-rw-r-- 1 raj raj 187 Jul 22 20:24 alarm.c -rw-rw-r-- 1 raj raj 226 Jul 22 20:22 background.c -rw-rw-r-- 1 raj raj 284 Jul 22 20:22 mychdir.c -rw-rw-r-- 1 raj raj 2058 Jul 22 20:23 vount.c -rwxrwxr-x 1 raj raj 4174 Jul 24 12:08 zombie -rw-rw-r-- 1 raj raj 298 Jul 22 20:20 zombie.c 2019/2/16 cs3320 49

Changing Directories: chdir() Every process has a current working directory Used when processing a relative path name A child process inherits the current working directory from its parent Example: when a utility is run from a shell, the utility process inherits the shell's current working directory 2019/2/16 cs3320 50

Changing Directories: chdir() int chdir(const char* pathname) Sets a process' current working directory to pathname The process must have execute permission from the directory for chdir() to succeed chdir() returns -1 if it fails 0 if it succeeds 2019/2/16 cs3320 51

Example Using chdir() #include <stdio.h> main () { /* Display current working directory */ system ("pwd"); /* Change working directory to root directory */ chdir ("/"); /* Display new working directory */ chdir ("/home/naveen"); /* Change again */ system ("pwd"); /* Display again */ } $ mychdir /home/raj/3320/ch12 / /home/naveen $

Changing Priorities: nice() Child process inherits priority of parent process Can change the priority using nice() int nice(int delta) Adds delta to the priority Legal values of priority -20 to +19 Only super user can change to negative priority. Smaller the priority value, faster the process will run. 2019/2/16 cs3320 53

Getting and Setting User and Group IDs: The get functions always succeed The set methods will succeed only when executed by super user or if id equals real or effective id of the process. uid_t getuid() uid_t setuid(uid_t id) uid_t geteuid() uid_t seteuid(uid_t id) gid_t getgid() uid_t setgid(gid_t id) gid_t getegid() uid_t setegid(gid_t id) 2019/2/16 cs3320 54