Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Uses of Pointers

Similar presentations


Presentation on theme: "Advanced Uses of Pointers"— Presentation transcript:

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

2 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.

3 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.

4 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.

5 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.

6 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.

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

8 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.

9 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.

10 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.

11 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.

12 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.

13 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.

14 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.

15 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.

16 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.

17 Process Management

18 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

19 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

20 A Tree of Processes on a Typical Solaris

21 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

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

23 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

24 Process States

25 Process Creation & Termination

26 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.

27 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

28 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

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

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

31 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)

32 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

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

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

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

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

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

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

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

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

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

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

43 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

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

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

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

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

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 raj raj Jul 22 20:24 alarm.c -rw-rw-r raj raj Jul 22 20:22 background.c -rw-rw-r raj raj Jul 22 20:22 mychdir.c -rw-rw-r raj raj Jul 22 20:23 vount.c -rwxrwxr-x 1 raj raj Jul 24 12:08 zombie -rw-rw-r raj raj Jul 22 20:20 zombie.c 2019/2/16 cs3320 49

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

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

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 $

52 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

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


Download ppt "Advanced Uses of Pointers"

Similar presentations


Ads by Google