Presentation is loading. Please wait.

Presentation is loading. Please wait.

– 1 – 15-213, F’02 Dynamic Memory Allocation Explicit vs. Implicit Memory Allocator Explicit: application allocates and frees space Implicit: application.

Similar presentations


Presentation on theme: "– 1 – 15-213, F’02 Dynamic Memory Allocation Explicit vs. Implicit Memory Allocator Explicit: application allocates and frees space Implicit: application."— Presentation transcript:

1 – 1 – 15-213, F’02 Dynamic Memory Allocation Explicit vs. Implicit Memory Allocator Explicit: application allocates and frees space Implicit: application allocates, but does not free spaceAllocation In both cases the memory allocator provides an abstraction of memory as a set of blocks Doles out free memory blocks to application Application Dynamic Memory Allocator Heap Memory

2 – 2 – 15-213, F’02 Process Memory Image kernel virtual memory Memory mapped region for shared libraries run-time heap (via malloc ) program text (. text ) initialized data (. data ) uninitialized data (. bss ) stack 0 %esp memory invisible to user code The “ brk ” ptr Allocators request additional heap memory from the operating system using the sbrk function.

3 – 3 – 15-213, F’02 Malloc Package #include #include void *malloc(size_t size) If successful: Returns a pointer to a memory block of at least size bytes, (typically) aligned to 8-byte boundary. If size == 0, returns NULL If unsuccessful: returns NULL (0) and sets errno. void free(void *p) Returns the block pointed at by p to pool of available memory p must come from a previous call to malloc or realloc. void *realloc(void *p, size_t size) Changes size of block p and returns pointer to new block. Contents of new block unchanged up to min of old and new size.

4 – 4 – 15-213, F’02 Assumptions Memory is word addressed (each word can hold a pointer) Allocated block (4 words) Free block (3 words) Free word Allocated word

5 – 5 – 15-213, F’02 Allocation Examples p1 = malloc(4) p2 = malloc(5) p3 = malloc(6) free(p2) p4 = malloc(2)

6 – 6 – 15-213, F’02 Constraints Applications: Can issue arbitrary sequence of allocation and free requests Free requests must correspond to an allocated blockAllocators Can’t control number or size of allocated blocks Must respond immediately to all allocation requests i.e., can’t reorder or buffer requests Must allocate blocks from free memory i.e., can only place allocated blocks in free memory Must align blocks so they satisfy all alignment requirements 8 byte alignment for GNU malloc ( libc malloc) on Linux boxes Can only manipulate and modify free memory Can’t move the allocated blocks once they are allocated i.e., compaction is not allowed

7 – 7 – 15-213, F’02 Goals of Good malloc/free Primary goals Good time performance for malloc and free Ideally should take constant time (not always possible) Should certainly not take linear time in the number of blocks Good space utilization User allocated structures should be large fraction of the heap. Want to minimize “fragmentation”. Some other goals Good locality properties Structures allocated close in time should be close in space “Similar” objects should be allocated close in space Robust Can check that free(p1) is on a valid allocated object p1 Can check that memory references are to allocated space

8 – 8 – 15-213, F’02 Internal Fragmentation Poor memory utilization caused by fragmentation. Comes in two forms: internal and external fragmentation Internal fragmentation For some block, internal fragmentation is the difference between the block size and the payload size. Caused by overhead of maintaining heap data structures, padding for alignment purposes, or explicit policy decisions (e.g., not to split the block). Depends only on the pattern of previous requests, and thus is easy to measure. payload Internal fragmentation block Internal fragmentation

9 – 9 – 15-213, F’02 External Fragmentation p1 = malloc(4) p2 = malloc(5) p3 = malloc(6) free(p2) p4 = malloc(6) oops! Occurs when there is enough aggregate heap memory, but no single free block is large enough External fragmentation depends on the pattern of future requests, and thus is difficult to measure.

10 – 10 – 15-213, F’02 Implementation Issues How do we know how much memory to free just given a pointer? How do we know how much memory to free just given a pointer? How do we keep track of the free blocks? How do we keep track of the free blocks? What do we do with the extra space when allocating a structure that is smaller than the free block it is placed in? What do we do with the extra space when allocating a structure that is smaller than the free block it is placed in? How do we pick a block to use for allocation -- many might fit? How do we pick a block to use for allocation -- many might fit? How do we reinsert freed block? How do we reinsert freed block? p1 = malloc(1) p0 free(p0)

11 – 11 – 15-213, F’02 Knowing How Much to Free Standard method Keep the length of a block in the word preceding the block. This word is often called the header field or header Requires an extra word for every allocated block free(p0) p0 = malloc(4)p0 Block sizedata 5

12 – 12 – 15-213, F’02 Keeping Track of Free Blocks Method 1: Implicit list using lengths -- links all blocks Method 2: Explicit list among the free blocks using pointers within the free blocks Method 3: Segregated free list Different free lists for different size classes Method 4: Blocks sorted by size Can use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key 5 426 5 426

13 – 13 – 15-213, F’02 Method 1: Implicit List Need to identify whether each block is free or allocated Can use extra bit Bit can be put in the same word as the size if block sizes are always multiples of two (mask out low order bit when reading size). size 1 word Format of allocated and free blocks payload a = 1: allocated block a = 0: free block size: block size payload: application data (allocated blocks only) a optional padding

14 – 14 – 15-213, F’02 Implicit List: Finding a Free Block First fit: Search list from beginning, choose first free block that fits Can take linear time in total number of blocks (allocated and free) In practice it can cause “splinters” at beginning of list Next fit: Like first-fit, but search list from location of end of previous search Research suggests that fragmentation is worse Best fit: Search the list, choose the free block with the closest size that fits Keeps fragments small --- usually helps fragmentation Will typically run slower than first-fit

15 – 15 – 15-213, F’02 Implicit List: Allocating in Free Block Allocating in a free block - splitting Since allocated space might be smaller than free space, we might want to split the block 4426 424 p 2 4 addblock(p, 2)

16 – 16 – 15-213, F’02 Implicit List: Freeing a Block Simplest implementation: Only need to clear allocated flag void free_block(ptr p) { *p = *p & -2} But can lead to “false fragmentation” There is enough free space, but the allocator won’t be able to find it 424 2 free(p) p 442 4 4 2 malloc(5) Oops!

17 – 17 – 15-213, F’02 Implicit List: Coalescing Join (coelesce) with next and/or previous block if they are free Coalescing with next block But how do we coalesce with previous block? 424 2 free(p) p 442 4 6

18 – 18 – 15-213, F’02 Implicit List: Bidirectional Coalescing Boundary tags [Knuth73] Replicate size/allocated word at bottom of free blocks Allows us to traverse the “list” backwards, but requires extra space Important and general technique! size 1 word Format of allocated and free blocks payload and padding a = 1: allocated block a = 0: free block size: total block size payload: application data (allocated blocks only) a sizea Boundary tag (footer) 44446464 Header

19 – 19 – 15-213, F’02 Constant Time Coalescing allocated free allocated free block being freed Case 1Case 2Case 3Case 4

20 – 20 – 15-213, F’02 m11 Constant Time Coalescing (Case 1) m11 n1 n1 m21 1 m11 1 n0 n0 m21 1

21 – 21 – 15-213, F’02 m11 Constant Time Coalescing (Case 2) m11 n+m20 0 m11 1 n1 n1 m20 0

22 – 22 – 15-213, F’02 m10 Constant Time Coalescing (Case 3) m10 n1 n1 m21 1 n+m10 0 m21 1

23 – 23 – 15-213, F’02 m10 Constant Time Coalescing (Case 4) m10 n1 n1 m20 0 n+m1+m20 0

24 – 24 – 15-213, F’02 Summary of Key Allocator Policies Placement policy: First fit, next fit, best fit, etc. Trades off lower throughput for less fragmentation Interesting observation: segregated free lists approximate a best fit placement policy without having to search entire free list. Splitting policy: When do we go ahead and split free blocks? How much internal fragmentation are we willing to tolerate? Coalescing policy: Immediate coalescing: coalesce adjacent blocks each time free is called Deferred coalescing: try to improve performance of free by deferring coalescing until needed. e.g., Coalesce as you scan the free list for malloc. Coalesce when the amount of external fragmentation reaches some threshold.

25 – 25 – 15-213, F’02 Keeping Track of Free Blocks Method 1: Implicit list using lengths -- links all blocks Method 1: Implicit list using lengths -- links all blocks Method 2: Explicit list among the free blocks using pointers within the free blocks Method 2: Explicit list among the free blocks using pointers within the free blocks Method 3: Segregated free lists Method 3: Segregated free lists Different free lists for different size classes Method 4: Blocks sorted by size (not discussed) Method 4: Blocks sorted by size (not discussed) Can use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key 5426 5426

26 – 26 – 15-213, F’02 Explicit Free Lists Use data space for link pointers Typically doubly linked Still need boundary tags for coalescing It is important to realize that links are not necessarily in the same order as the blocks ABC 4444664444 Forward links Back links A B C

27 – 27 – 15-213, F’02 Allocating From Explicit Free Lists free block predsucc free block predsucc Before: After: (with splitting)

28 – 28 – 15-213, F’02 Freeing With Explicit Free Lists Insertion policy: Where in the free list do you put a newly freed block? LIFO (last-in-first-out) policy Insert freed block at the beginning of the free list Pro: simple and constant time Con: studies suggest fragmentation is worse than address ordered. Address-ordered policy Insert freed blocks so that free list blocks are always in address order »i.e. addr(pred) < addr(curr) < addr(succ) Con: requires search Pro: studies suggest fragmentation is better than LIFO

29 – 29 – 15-213, F’02 Explicit List Summary Comparison to implicit list: Allocate is linear time in number of free blocks instead of total blocks -- much faster allocates when most of the memory is full Slightly more complicated allocate and free since needs to splice blocks in and out of the list Some extra space for the links (2 extra words needed for each block) Main use of linked lists is in conjunction with segregated free lists Keep multiple linked lists of different size classes, or possibly for different types of objects

30 – 30 – 15-213, F’02 Keeping Track of Free Blocks Method 1: Implicit list using lengths -- links all blocks Method 2: Explicit list among the free blocks using pointers within the free blocks Method 3: Segregated free list Different free lists for different size classes Method 4: Blocks sorted by size Can use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key 5 426 5 426

31 – 31 – 15-213, F’02 Segregated Storage Each size class has its own collection of blocks 1-2 3 4 5-8 9-16 Often have separate size class for every small size (2,3,4,…) For larger sizes typically have a size class for each power of 2

32 – 32 – 15-213, F’02 Simple Segregated Storage Separate heap and free list for each size class No splitting To allocate a block of size n: If free list for size n is not empty, allocate first block on list (note, list can be implicit or explicit) If free list is empty, get a new page create new free list from all blocks in page allocate first block on list Constant time To free a block: Add to free list If page is empty, return the page for use by another size (optional)Tradeoffs: Fast, but can fragment badly

33 – 33 – 15-213, F’02 Segregated Fits Array of free lists, each one for some size class To allocate a block of size n: Search appropriate free list for block of size m > n If an appropriate block is found: Split block and place fragment on appropriate list (optional) If no block is found, try next larger class Repeat until block is found To free a block: Coalesce and place on appropriate list (optional)Tradeoffs Faster search than sequential fits (i.e., log time for power of two size classes) Controls fragmentation of simple segregated storage Coalescing can increase search times Deferred coalescing can help

34 – 34 – 15-213, F’02 Implicit Memory Management: Garbage Collection Garbage collection: automatic reclamation of heap- allocated storage -- application never has to free Common in functional languages, scripting languages, and modern object oriented languages: Lisp, ML, Java, Perl, Mathematica, Variants (conservative garbage collectors) exist for C and C++ Cannot collect all garbage void foo() { int *p = malloc(128); return; /* p block is now garbage */ }

35 – 35 – 15-213, F’02 Garbage Collection How does the memory manager know when memory can be freed? In general we cannot know what is going to be used in the future since it depends on conditionals But we can tell that certain blocks cannot be used if there are no pointers to them Need to make certain assumptions about pointers Memory manager can distinguish pointers from non- pointers All pointers point to the start of a block Cannot hide pointers (e.g., by coercing them to an int, and then back again)

36 – 36 – 15-213, F’02 Classical GC algorithms Mark and sweep collection (McCarthy, 1960) Does not move blocks (unless you also “compact”) Reference counting (Collins, 1960) Does not move blocks (not discussed) Copying collection (Minsky, 1963) Moves blocks (not discussed) For more information, see Jones and Lin, “Garbage Collection: Algorithms for Automatic Dynamic Memory”, John Wiley & Sons, 1996.

37 – 37 – 15-213, F’02 Memory as a Graph We view memory as a directed graph Each block is a node in the graph Each pointer is an edge in the graph Locations not in the heap that contain pointers into the heap are called root nodes (e.g. registers, locations on the stack, global variables) Root nodes Heap nodes Not-reachable (garbage) reachable A node (block) is if there is a path from any root to that node. A node (block) is reachable if there is a path from any root to that node. Non-reachable nodes are garbage (never needed by the application)

38 – 38 – 15-213, F’02 Application new(n) : returns pointer to new block with all locations cleared read(b,i): read location i of block b into register write(b,i,v): write v into location i of block b Each block will have a header word addressed as b[-1], for a block b Used for different purposes in different collectors Instructions used by the Garbage Collector is_ptr(p): d etermines whether p is a pointer length(b ): returns the length of block b, not including the header get_roots() : returns all the roots

39 – 39 – 15-213, F’02 Mark and Sweep Collecting Can build on top of malloc/free package Allocate using malloc until you “run out of space” When out of space: Use extra mark bit in the head of each block Mark: Start at roots and set mark bit on all reachable memory Sweep: Scan all blocks and free blocks that are not marked Before mark root After mark After sweep free Mark bit set free

40 – 40 – 15-213, F’02 Conservative Mark and Sweep in C A conservative collector for C programs Is_ptr() determines if a word is a pointer by checking if it points to an allocated block of memory. But, in C pointers can point to the middle of a block. So how do we find the beginning of the block? Can use balanced tree to keep track of all allocated blocks where the key is the location Balanced tree pointers can be stored in header (use two additional words) header ptr headdata leftright size

41 – 41 – 15-213, F’02 Memory-Related Bugs Dereferencing bad pointers Reading uninitialized memory Overwriting memory Referencing nonexistent variables Freeing blocks multiple times Referencing freed blocks Failing to free blocks

42 – 42 – 15-213, F’02 Dereferencing Bad Pointers The classic scanf bug scanf(“%d”, val);

43 – 43 – 15-213, F’02 Reading Uninitialized Memory Assuming that heap data is initialized to zero /* return y = Ax */ int *matvec(int **A, int *x) { int *y = malloc(N*sizeof(int)); int i, j; for (i=0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4258072/slides/slide_43.jpg", "name": "– 43 – 15-213, F’02 Reading Uninitialized Memory Assuming that heap data is initialized to zero /* return y = Ax */ int *matvec(int **A, int *x) { int *y = malloc(N*sizeof(int)); int i, j; for (i=0; i

44 – 44 – 15-213, F’02 Overwriting Memory Allocating the (possibly) wrong sized object int **p; p = malloc(N*sizeof(int)); for (i=0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4258072/slides/slide_44.jpg", "name": "– 44 – 15-213, F’02 Overwriting Memory Allocating the (possibly) wrong sized object int **p; p = malloc(N*sizeof(int)); for (i=0; i

45 – 45 – 15-213, F’02 Overwriting Memory Off-by-one error int **p; p = malloc(N*sizeof(int *)); for (i=0; i<=N; i++) { p[i] = malloc(M*sizeof(int)); }

46 – 46 – 15-213, F’02 Overwriting Memory Not checking the max string size Basis for classic buffer overflow attacks 1988 Internet worm Modern attacks on Web servers char s[8]; int i; gets(s); /* reads “123456789” from stdin */

47 – 47 – 15-213, F’02 Overwriting Memory Referencing a pointer instead of the object it points to int *BinheapDelete(int **binheap, int *size) { int *packet; packet = binheap[0]; binheap[0] = binheap[*size - 1]; *size--; Heapify(binheap, *size, 0); return(packet); }

48 – 48 – 15-213, F’02 Overwriting Memory Misunderstanding pointer arithmetic int *search(int *p, int val) { while (*p && *p != val) p += sizeof(int); return p; }

49 – 49 – 15-213, F’02 Referencing Nonexistent Variables Forgetting that local variables disappear when a function returns int *foo () { int val; return &val; }

50 – 50 – 15-213, F’02 Referencing Freed Blocks x = malloc(N*sizeof(int)); free(x);... y = malloc(M*sizeof(int)); for (i=0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4258072/slides/slide_50.jpg", "name": "– 50 – 15-213, F’02 Referencing Freed Blocks x = malloc(N*sizeof(int)); free(x);...", "description": "y = malloc(M*sizeof(int)); for (i=0; i

51 – 51 – 15-213, F’02 Failing to Free Blocks (Memory Leaks) Slow, long-term killer! foo() { int *x = malloc(N*sizeof(int));... return; }

52 – 52 – 15-213, F’02 Failing to Free Blocks (Memory Leaks) Freeing only part of a data structure struct list { int val; struct list *next; }; foo() { struct list *head = malloc(sizeof(struct list)); head->val = 0; head->next = NULL;... free(head); return; }

53 – 53 – 15-213, F’02 Dynamic and Virtual Memory real life example Target machine: IBM power 5 at LLNL

54 – 54 – 15-213, F’02 Exceptional Control Flow Mechanisms for exceptional control flow exists at all levels of a computer system. Low level Mechanism exceptions change in control flow in response to a system event (i.e., change in system state) Combination of hardware and OS software Higher Level Mechanisms Process context switch Signals Nonlocal jumps (setjmp/longjmp) Implemented by either: OS software (context switch and signals). C language runtime library: nonlocal jumps.

55 – 55 – 15-213, F’02 Exceptions An exception is a transfer of control to the OS in response to some event (i.e., change in processor state) User ProcessOS exception exception processing by exception handler exception return (optional) event current next

56 – 56 – 15-213, F’02 Interrupt Vectors Each type of event has a unique exception number k Index into jump table (a.k.a., interrupt vector) Jump table entry k points to a function (exception handler). Handler k is called each time exception k occurs. interrupt vector 0 1 2... n-1 code for exception handler 0 code for exception handler 0 code for exception handler 1 code for exception handler 1 code for exception handler 2 code for exception handler 2 code for exception handler n-1 code for exception handler n-1... Exception numbers

57 – 57 – 15-213, F’02 Asynchronous Exceptions (Interrupts) Caused by events external to the processor Indicated by setting the processor’s interrupt pin handler returns to “next” instruction.Examples: I/O interrupts hitting ctl-c at the keyboard arrival of a packet from a network arrival of a data sector from a disk Hard reset interrupt hitting the reset button Soft reset interrupt hitting ctl-alt-delete on a PC

58 – 58 – 15-213, F’02 0x00000100 irmovl $300,rA 0x00000106 irmovl $3,rB 0x0000010C irmov $10,rC 0x00000112 addl rC,rB 0x00000114 rmmovl rB,(rA) The jump table 1 0x10000000 2 0x10001000 3 0x10003000 4 0x10004000 hardware interrupt 3 came while addl hardware interrupt 3 came while addl call getKB mrmovl 0x00000000,rA rmmovl rB,(rA)

59 – 59 – 15-213, F’02 0x10003000 push CFLAGS 0x10003002 push rA 0x10003004 push rB 0x10003006 push rC 0x10003008 push rD 0x1000300a push rE 0x1000300c call getKB 0x10003011 mrmovl 0x0,rA 0x10003017 rmmovl rB,(rA) 0x1000301d pop rE 0x1000301f pop rD 0x10003021 pop rC 0x10003023 pop rB 0x10003025 pop rA 0x10003027 pop CFLAFS

60 – 60 – 15-213, F’02 Synchronous Exceptions Caused by events that occur as a result of executing an instruction: Traps Intentional Examples: system calls, breakpoint traps, special instructions Returns control to “next” instruction Faults Unintentional but possibly recoverable Examples: page faults (recoverable), protection faults (unrecoverable). Either re-executes faulting (“current”) instruction or aborts. Aborts unintentional and unrecoverable Examples: parity error, machine check. Aborts current program

61 – 61 – 15-213, F’02 Trap Example User ProcessOS exception Open file return int pop Opening a File User calls open(filename, options) Function open executes system call instruction int OS must find or create file, get it ready for reading or writing Returns integer file descriptor 0804d070 :... 804d082:cd 80 int $0x80 804d084:5b pop %ebx...

62 – 62 – 15-213, F’02 Fault Example #1 User ProcessOS page fault Create page and load into memory return event movl Memory Reference User writes to memory location That portion (page) of user’s memory is currently on disk Page handler must load page into physical memory Returns to faulting instruction Successful on second try int a[1000]; main () { a[500] = 13; } 80483b7:c7 05 10 9d 04 08 0d movl $0xd,0x8049d10

63 – 63 – 15-213, F’02 Fault Example #2 User ProcessOS page fault Detect invalid address event movl Memory Reference User writes to memory location Address is not valid Page handler detects invalid address Sends SIGSEG signal to user process User process exits with “segmentation fault” int a[1000]; main () { a[5000] = 13; } 80483b7:c7 05 60 e3 04 08 0d movl $0xd,0x804e360 Signal process

64 – 64 – 15-213, F’02 Processes Def: A process is an instance of a running program. One of the most profound ideas in computer science. 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

65 – 65 – 15-213, F’02 Logical Control Flows Time Process AProcess BProcess C Each process has its own logical control flow

66 – 66 – 15-213, F’02 User View of Concurrent Processes Control flows for concurrent processes are physically disjoint in time. However, we can think of concurrent processes are running in parallel with each other. Time Process AProcess BProcess C

67 – 67 – 15-213, F’02 Context Switching Processes are managed by a shared chunk of OS code called the kernel Important: the kernel is not a separate process, but rather runs as part of some user process Control flow passes from one process to another via a context switch. Process A code Process B code user code kernel code user code kernel code user code Time context switch

68 – 68 – 15-213, F’02 Private Address Spaces Each process has its own private address space. kernel virtual memory (code, data, heap, stack) memory mapped region for shared libraries run-time heap (managed by malloc) user stack (created at runtime) unused 0 %esp (stack pointer) memory invisible to user code brk 0xc0000000 0x08048000 0x40000000 read/write segment (.data,.bss) read-only segment (.init,.text,.rodata) loaded from the executable file 0xffffffff

69 – 69 – 15-213, F’02 fork : Creating new processes int fork(void) creates a new process (child process) that is identical to the calling process (parent process) returns 0 to the child process returns child’s pid to the parent process if (fork() == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } Fork is interesting (and often confusing) because it is called once but returns twice

70 – 70 – 15-213, F’02 Fork Example #1 void fork1() { int x = 1; pid_t pid = fork(); if (pid == 0) { printf("Child has x = %d\n", ++x); } else { printf("Parent has x = %d\n", --x); } printf("Bye from process %d with x = %d\n", getpid(), x); } Key Points Parent and child both run same code Distinguish parent from child by return value from fork Start with same state, but each has private copy Including shared output file descriptor Relative ordering of their print statements undefined

71 – 71 – 15-213, F’02 Fork Example #2 void fork2() { printf("L0\n"); fork(); printf("L1\n"); fork(); printf("Bye\n"); } Key Points Both parent and child can continue forking L0 L1 Bye

72 – 72 – 15-213, F’02 User View of Concurrent Processes Control flows for concurrent processes are physically disjoint in time. However, we can think of concurrent processes are running in parallel with each other. Time Process AProcess BProcess C

73 – 73 – 15-213, F’02 Context Switching Processes are managed by a shared chunk of OS code called the kernel Important: the kernel is not a separate process, but rather runs as part of some user process Control flow passes from one process to another via a context switch. Process A code Process B code user code kernel code user code kernel code user code Time context switch

74 – 74 – 15-213, F’02 Private Address Spaces Each process has its own private address space. kernel virtual memory (code, data, heap, stack) memory mapped region for shared libraries run-time heap (managed by malloc) user stack (created at runtime) unused 0 %esp (stack pointer) memory invisible to user code brk 0xc0000000 0x08048000 0x40000000 read/write segment (.data,.bss) read-only segment (.init,.text,.rodata) loaded from the executable file 0xffffffff

75 – 75 – 15-213, F’02 fork : Creating new processes int fork(void) creates a new process (child process) that is identical to the calling process (parent process) returns 0 to the child process returns child’s pid to the parent process if (fork() == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } Fork is interesting (and often confusing) because it is called once but returns twice

76 – 76 – 15-213, F’02 Fork Example #1 void fork1() { int x = 1; pid_t pid = fork(); if (pid == 0) { printf("Child has x = %d\n", ++x); } else { printf("Parent has x = %d\n", --x); } printf("Bye from process %d with x = %d\n", getpid(), x); } Key Points Parent and child both run same code Distinguish parent from child by return value from fork Start with same state, but each has private copy Including shared output file descriptor Relative ordering of their print statements undefined

77 – 77 – 15-213, F’02 Fork Example #2 void fork2() { printf("L0\n"); fork(); printf("L1\n"); fork(); printf("Bye\n"); } Key Points Both parent and child can continue forking L0 L1 Bye

78 – 78 – 15-213, F’02 Fork Example #3 void fork3() { printf("L0\n"); fork(); printf("L1\n"); fork(); printf("L2\n"); fork(); printf("Bye\n"); } Key Points Both parent and child can continue forking L1L2 Bye L1L2 Bye L0

79 – 79 – 15-213, F’02 Fork Example #4 void fork4() { printf("L0\n"); if (fork() != 0) { printf("L1\n"); if (fork() != 0) { printf("L2\n"); fork(); } printf("Bye\n"); } Key Points Both parent and child can continue forking L0 L1 Bye L2 Bye

80 – 80 – 15-213, F’02 Fork Example #5 void fork5() { printf("L0\n"); if (fork() == 0) { printf("L1\n"); if (fork() == 0) { printf("L2\n"); fork(); } printf("Bye\n"); } Key Points Both parent and child can continue forking L0 Bye L1 Bye L2

81 – 81 – 15-213, F’02 exit : Destroying Process void exit(int status) exits a process Normally return with status 0 atexit() registers functions to be executed upon exit void cleanup(void) { printf("cleaning up\n"); } void fork6() { atexit(cleanup); fork(); exit(0); }

82 – 82 – 15-213, F’02 Zombies Idea When process terminates, still consumes system resources Various tables maintained by OS Called a “zombie” Living corpse, half alive and half deadReaping Performed by parent on terminated child Parent is given exit status information Kernel discards process What if Parent Doesn’t Reap? If any parent terminates without reaping a child, then child will be reaped by init process Only need explicit reaping for long-running processes E.g., shells and servers

83 – 83 – 15-213, F’02 wait : Synchronizing with children int wait(int *child_status) suspends current process until one of its children terminates return value is the pid of the child process that terminated if child_status != NULL, then the object it points to will be set to a status indicating why the child process terminated

84 – 84 – 15-213, F’02 Signals A signal is a small message that notifies a process that an event of some type has occurred in the system. Kernel abstraction for exceptions and interrupts. Sent from the kernel (sometimes at the request of another process) to a process. Different signals are identified by small integer ID’s The only information in a signal is its ID and the fact that it arrived. IDName Default Action Corresponding Event 2SIGINTTerminate Interrupt from keyboard ( ctl-c ) 9SIGKILLTerminate Kill program (cannot override or ignore) 11SIGSEGV Terminate & Dump Segmentation violation 14SIGALRMTerminate Timer signal 17SIGCHLDIgnore Child stopped or terminated

85 – 85 – 15-213, F’02 Signal Concepts Sending a signal Kernel sends (delivers) a signal to a destination process by updating some state in the context of the destination process. Kernel sends a signal for one of the following reasons: Kernel has detected a system event such as divide-by-zero (SIGFPE) or the termination of a child process (SIGCHLD) Another process has invoked the kill system call to explicitly request the kernel to send a signal to the destination process.

86 – 86 – 15-213, F’02 Signal Concepts (cont) Receiving a signal A destination process receives a signal when it is forced by the kernel to react in some way to the delivery of the signal. Three possible ways to react: Ignore the signal (do nothing) Terminate the process. Catch the signal by executing a user-level function called a signal handler. »Akin to a hardware exception handler being called in response to an asynchronous interrupt.

87 – 87 – 15-213, F’02 Signal Concepts (cont) A signal is pending if it has been sent but not yet received. There can be at most one pending signal of any particular type. Important: Signals are not queued If a process has a pending signal of type k, then subsequent signals of type k that are sent to that process are discarded. A process can block the receipt of certain signals. Blocked signals can be delivered, but will not be received until the signal is unblocked. A pending signal is received at most once.

88 – 88 – 15-213, F’02 Signal Concepts Kernel maintains pending and blocked bit vectors in the context of each process. pending – represents the set of pending signals Kernel sets bit k in pending whenever a signal of type k is delivered. Kernel clears bit k in pending whenever a signal of type k is received blocked – represents the set of blocked signals Can be set and cleared by the application using the sigprocmask function.

89 – 89 – 15-213, F’02 Process Groups Every process belongs to exactly one process group Fore- ground job Back- ground job #1 Back- ground job #2 Shell Child pid=10 pgid=10 Foreground process group 20 Background process group 32 Background process group 40 pid=20 pgid=20 pid=32 pgid=32 pid=40 pgid=40 pid=21 pgid=20 pid=22 pgid=20 getpgrp() – Return process group of current process setpgid() – Change process group of a process

90 – 90 – 15-213, F’02 Sending Signals with kill Function void fork12() { pid_t pid[N]; int i, child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) while(1); /* Child infinite loop */ /* Parent terminates the child processes */ for (i = 0; i < N; i++) { printf("Killing process %d\n", pid[i]); kill(pid[i], SIGINT); } /* Parent reaps terminated children */ for (i = 0; i < N; i++) { pid_t wpid = wait(&child_status); if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status)); else printf("Child %d terminated abnormally\n", wpid); }

91 – 91 – 15-213, F’02 Receiving Signals Suppose kernel is returning from exception handler and is ready to pass control to process p. Kernel computes pnb = pending & ~blocked The set of pending nonblocked signals for process p If ( pnb == 0 ) Pass control to next instruction in the logical flow for p.Else Choose least nonzero bit k in pnb and force process p to receive signal k. The receipt of the signal triggers some action by p Repeat for all nonzero k in pnb. Pass control to next instruction in logical flow for p.

92 – 92 – 15-213, F’02 Default Actions Each signal type has a predefined default action, which is one of: The process terminates The process terminates and dumps core. The process stops until restarted by a SIGCONT signal. The process ignores the signal.

93 – 93 – 15-213, F’02 Installing Signal Handlers The signal function modifies the default action associated with the receipt of signal signum : handler_t *signal(int signum, handler_t *handler) Different values for handler : SIG_IGN: ignore signals of type signum SIG_DFL: revert to the default action on receipt of signals of type signum. Otherwise, handler is the address of a signal handler Called when process receives signal of type signum Referred to as “installing” the handler. Executing handler is called “catching” or “handling” the signal. When the handler executes its return statement, control passes back to instruction in the control flow of the process that was interrupted by receipt of the signal.

94 – 94 – 15-213, F’02 Signal Handling Example void int_handler(int sig) { printf("Process %d received signal %d\n", getpid(), sig); exit(0); } void fork13() { pid_t pid[N]; int i, child_status; signal(SIGINT, int_handler);... } linux>./forks 13 Killing process 24973 Killing process 24974 Killing process 24975 Killing process 24976 Killing process 24977 Process 24977 received signal 2 Child 24977 terminated with exit status 0 Process 24976 received signal 2 Child 24976 terminated with exit status 0 Process 24975 received signal 2 Child 24975 terminated with exit status 0 Process 24974 received signal 2 Child 24974 terminated with exit status 0 Process 24973 received signal 2 Child 24973 terminated with exit status 0 linux>

95 – 95 – 15-213, F’02 A Program That Reacts to Externally Generated Events (ctrl-c) #include void handler(int sig) { printf(“caught sigint \n"); exit(0); } main() { signal(SIGINT, handler); /* installs ctl-c handler */ while(1) { }

96 – 96 – 15-213, F’02 A Program That Reacts to Internally Generated Events #include int beeps = 0; /* SIGALRM handler */ void handler(int sig) { printf("BEEP\n"); fflush(stdout); if (++beeps < CNT) alarm(1); else { printf("BOOM!\n"); exit(0); } main() { signal(SIGALRM, handler); alarm(1); /* send SIGALRM in 1 second */ while (1) { /* handler returns here */ } linux> a.out BEEP BOOM! bass>


Download ppt "– 1 – 15-213, F’02 Dynamic Memory Allocation Explicit vs. Implicit Memory Allocator Explicit: application allocates and frees space Implicit: application."

Similar presentations


Ads by Google