Introduction to Computer Systems 15-213/18-243, spring 2009 ...

Introduction to Computer Systems 15-213/18-243, spring 2009 ...

Processes Spring 2016 Roadmap C: Java: car *c = malloc(sizeof(car)); c->miles = 100; c->gals = 17; float mpg = get_mpg(c); free(c); Car c = new Car(); c.setMiles(100); c.setGals(17); float mpg = c.getMPG(); Assembl y languag e: get_mpg: pushq movq ... popq ret Machine code: 0111010000011000 100011010000010000000010 1000100111000010 110000011111101000011111

Comput er system: %rbp %rsp, %rbp %rbp OS: Data & addressing Integers & floats Machine code &C x86 assembly Procedures & stacks Arrays & structs Memory & caches Processes Virtual memory Memory allocation Java vs. C 1 Processes Spring 2016 Processes: another important abstraction

First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies 2 Processes Spring 2016 Control Flow So far, weve seen how the flow of control changes as a single program executes But there are multiple programs running concurrently we also need to understand how control flows across the many components of the system In particular: More programs running than CPUs Exceptional control flow is the basic mechanism used for: Transferring control between processes and OS

Handling I/O and virtual memory within the OS Implementing multi-process applications like shells and web servers Implementing concurrency 3 Processes Spring 2016 Control Flow Processors do only one thing: From startup to shutdown, a CPU simply reads and executes (interprets) a sequence of instructions, one at a time This sequence is the CPUs control flow (or flow of control) Physical control flow time inst1 inst2 inst3 instn 4 Processes Spring 2016 Altering the Control Flow Up to now: two ways to change control flow: Jumps (conditional and unconditional)

Call and return Both react to changes in program state Processor also needs to react to changes in system state user hits Ctrl-C at the keyboard user clicks on a different applications window on the screen data arrives from a disk or a network adapter instruction divides by zero system timer expires Can jumps and procedure calls achieve this? Jumps and calls are not sufficient the system needs mechanisms for exceptional control flow! 5 Processes Spring 2016 Java Digression #1 Java has exceptions, but theyre something different E.g., NullPointerException, MyBadThingHappenedException, throw statements try/catch statements (throw to youngest matching catch on the call-stack, or exit-with-stack-trace if none)

Java exceptions are for reacting to (unexpected) program state Can be implemented with stack operations and conditional jumps A mechanism for many call-stack returns at once Requires additions to the calling convention, but we already have the CPU features we need System-state changes on previous slide are mostly of a different sort 6 Processes Spring 2016 Exceptional Control Flow Exists at all levels of a computer system Low level mechanisms Exceptions Change in processors control flow in response to a system event (i.e., change in system state, user-generated interrupt) Implemented using a combination of hardware and OS software Higher level mechanisms Process context switch

Implemented by OS software and hardware timer Signals youll hear about these in CSE451 and CSE/EE 466 474 Implemented by OS software Well talk about exceptions and process context switch 7 Processes Spring 2016 Processes First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies

8 Processes Spring 2016 Exceptions An exception is transfer of control to the operating system (OS) kernel in response to some event (i.e., change in processor state) Kernel is the memory-resident part of the OS Examples of events: div by 0, page fault, I/O request completes, Ctrl-C User Code even t current_instr next_instr OS Kernel Code exception exception processing by exception handler, return tothen: current_instr, O return to next_instr, OR abort How does the system know where to jump to in the OS?

9 Processes Spring 2016 Exception Table: a jump table for exceptions Exception numbers Excepti on Table 0 1 2 n1 code for exception handler 0 Each type of event has a unique exception number k k = index into exception table (a.k.a. interrupt vector)

Handler k is called each time exception k occurs code for exception handler 1 code for exception handler 2 ... code for exception handler n-1 Also called: Interrupt Vector Table 10 Processes Spring 2016 Exception Table (Excerpt) Exception Number Description Exception Class 0 Divide error Fault 13 General protection fault Fault

14 Page fault Fault 18 Machine check Abort 32-255 OS-defined Interrupt or trap 11 Processes Spring 2016 Types of Exceptions Asynchronous Exceptions (Interrupts) - Caused by events external to the processor Synchronous Exceptions Caused by events that occur as a result of executing an instruction Traps - Intentional Faults - Unintentional Aborts - Unintentional 12

Processes Spring 2016 Processes First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies 13 Processes Spring 2016 Asynchronous Exceptions (Interrupts) Caused by events external to the processor Indicated by setting the processors interrupt pin(s) (wire into CPU) After interrupt handler runs, the handler returns to next instruction

Examples: I/O interrupts Hitting Ctrl-C on the keyboard Clicking a mouse button or tapping a touchscreen Arrival of a packet from a network Arrival of data from a disk Timer interrupt Every few ms, an external timer chip triggers an interrupt Used by the OS kernel to take back control from user programs 14 Processes Spring 2016 Synchronous Exceptions Caused by events that occur as a result of executing an instruction: Traps Intentional: transfer control to OS to perform some function Examples: system calls, breakpoint traps, special instructions

Returns control to next instruction Faults Unintentional but possibly recoverable Examples: page faults, segment protection faults, integer divide-by-zero exceptions Either re-executes faulting (current) instruction or aborts Aborts Unintentional and unrecoverable Examples: parity error, machine check (hardware failure detected) Aborts current program 15 Processes Spring 2016 System Calls Each system call has a unique ID number Examples for Linux on x86-64: Number Name Description

0 read Read file 1 write Write file 2 open Open file 3 close Close file 4 stat Get info about file 57 fork Create process 59 execve

Execute a program 60 _exit Terminate process 62 kill Send signal to process 16 Traps: System Call Example: Opening File Processes Spring 2016 User calls: open(filename, options) Calls __open function, which invokes system call instruction syscall 00000000000e5d70 <__open>: ... e5d79: b8 02 00 00 00 e5d7e: 0f 05 e5d80: 48 3d 01 f0 ff ff ... e5dfa: c3

User code mov $0x2,%eax # open is syscall #2 syscall # Return value in %rax cmp $0xfffffffffffff001,%rax retq OS Kernel code syscall cmp Exception Open file Returns %rax contains syscall number Other arguments in %rdi, %rsi, %rdx, %r10, %r8, %r9 Return value in %rax Negative value is an error corresponding to 17 Processes Spring 2016 Spoiler Alert!

Fault Example: Page Fault User writes to memory location That portion (page) of users memory is currently on disk 80483b7: c7 05 10 9d 04 08 0d User code movl $0xd,0x8049d10 OS Kernel code exception: page fault handle_page_fault: returns movl int a[1000]; int main() { a[500] = 13; } Create page and load into memory

Page fault handler must load page into physical memory Returns to faulting instruction: mov is executed again! Successful on second try 18 Processes Spring 2016 Fault Example: Invalid Memory Reference int a[1000]; int main() { a[5000] = 13; } 80483b7: c7 05 60 e3 04 08 0d User Process movl $0xd,0x804e360 OS exception: page fault handle_page_fault: signal process movl

detect invalid address Page fault handler detects invalid address Sends SIGSEGV signal to user process User process exits with segmentation fault 19 Processes Spring 2016 Summary Exceptions Events that require non-standard control flow Generated externally (interrupts) or internally (traps and faults) After an exception is handled, one of three things may happen: Re-execute the current instruction Resume execution with the next instruction Abort the process that caused the exception 20 Processes Spring 2016 Java Digression #2 Recall: Java exceptions are [just] pop all the way to the nearest matching catch statement Fully explains throw new MyParticularException()

Java language defines built-in exceptions like ArrayBoundsException and NullPointerException Not so special: just means a[i] and e.f and e.m() have to be compiled to include checking for exceptional case Slower but safer than C! Array-bounds: Array-pointed-to has a length field Null-pointer: Represent null as 0 Just like C, but type system prevents using it in if-statements, etc. 21 Processes Spring 2016 A 351-worthy trick In principle, implement Javas e.f as Cs tmp = e; tmp ? tmp->f : throw NullPointerException (This is the idea; C doesnt actually have exceptions) In practice, thats lots of extra code and branches, so do this instead: Just execute tmp->f But install SIGSEGV trap handler that recognizes 0 and modifies program state to make the exception happen (Traps are very slow, but null-pointer exceptions should be very rare, so this is a good engineering trade-off) 22 Processes

Spring 2016 Processes First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies May 14 23 Processes Spring 2016 Its an illusion. What is a process? Process 1 Memory Stack Heap Data

Code CPU Registers%rip Disk Chrome.ex e 24 Processes Spring 2016 Its an illusion. What is a process? Computer Process 3 Memory Stack Process 2 Memory Stack Heap Data Code Process 1 Memory Stack CPU Registe rs Heap

Data Code CPU Registe rs Process 4 Memory Stack Heap Data Code Heap Data Code CPU CPU Registe rs Registe rs CPU Disk /Applications/ Chrome.ex e Slack.ex e PowerPoint.ex

e 25 Processes Spring 2016 Its an illusion. What is a process? Computer Process 3 Memory Stack Process 2 Memory Stack Heap Data Code Process 1 Memory Stack CPU Registe rs Operatin g System Disk Heap Data

Code CPU Registe rs Process 4 Memory Stack Heap Data Code Heap Data Code CPU CPU Registe rs Registe rs CPU /Applications/ Chrome.ex e Slack.ex e PowerPoint.ex e 26

Processes Spring 2016 What is a process? Processes are another abstraction in our computer system Provided by the OS OS uses a data structure to represent each process Maintains the interface between the program and the underlying hardware (CPU + memory) What do processes have to do with exceptional control flow? Exceptional control flow is the mechanism the OS uses to enable multiple processes to run on the same system. What is the difference between: a processor? a program? a process? 27 Processes Spring 2016 Processes Definition: 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 Memor abstractions: Logical control flow y Stack Each program seems to have exclusive use of the CPU Heap Provided by kernel mechanism called context switching Data Code Private address space Each program seems to have exclusive use of main CPU memory Registe Provided by kernel mechanism called virtual memory rs 28 Processes Spring 2016 Multiprocessing: The Illusion Memor y Stack Memor y Stack

Memor y Stack Heap Data Code Heap Data Code Heap Data Code CPU CPU Registe rs Registe rs CPU Registe rs Computer runs many processes simultaneously Applications for one or more users

Web browsers, email clients, editors, Background tasks Monitoring network & I/O devices 29 Processes Spring 2016 Multiprocessing: The Reality Memory Stack Heap Data Code Saved registe rs Stack Heap Data Code Saved registe rs Stack Heap Data Code Saved registe rs

CPU Registe rs Single processor executes multiple processes concurrently Process executions interleaved, CPU runs one at a time Address spaces managed by virtual memory system (later in course) Execution context (register values, stack, ) for other processes saved in memory 30 Processes Spring 2016 Multiprocessing Memory Stack Heap Data Code Saved registe rs Stack Heap Data Code Saved registe rs Stack Heap

Data Code Saved registe rs CPU Registe rs Context switch Save current registers in memory 31 Processes Spring 2016 Multiprocessing Memory Stack Heap Data Code Saved registe rs Stack Heap Data Code Saved registe rs

Stack Heap Data Code Saved registe rs CPU Registe rs Context switch Save current registers in memory Schedule next process for execution 32 Processes Spring 2016 Multiprocessing Memory Stack Heap Data Code Saved registe rs Stack Heap Data Code Saved registe

rs Stack Heap Data Code Saved registe rs CPU Registe rs Context switch Save current registers in memory Schedule next process for execution Load saved registers and switch address space 33 Processes Spring 2016 Multiprocessing: The (Modern) Reality Memory Stack Heap Data Code Saved registe rs

CPU Registe rs Stack Heap Data Code Saved registe rs CPU Registe rs Stack Heap Data Code Saved registe rs Multicore processors Multiple CPUs (cores) on single chip Share main memory (and some of the caches) Each can execute a separate process Kernel schedules processes to

cores 34 Processes Concurrent Processes Spring 2016 Assume only one CPU Each process is a logical control flow Two processes run concurrently (are concurrent) if their instruction executions (flows) overlap in time Otherwise, they are sequential Examples (running on single core): Concurrent: A & B, A & C Sequential: B & C (B ends before C starts) Process A Process B Process C tim e 35 Processes Spring 2016 Assume only one CPU Users View of Concurrent

Processes Control flows for concurrent processes are physically disjoint in time CPU only executes instructions for one process at a time However, the user can think of concurrent processes as executing at the same time, in parallel Process A Process B Process C time 36 Processes Context Switching Spring 2016 Assume only one CPU Processes are managed by a shared chunk of OS code called the kernel The kernel is not a separate process, but rather runs as part of a user process Process 1 Kernel code / data

Memor y Stack Heap Data Code CPU Registe rs 37 Processes Context Switching Spring 2016 Assume only one CPU Processes are managed by a shared chunk of OS code called the kernel The kernel is not a separate process; runs as part of a user process Control flow passes from one process to another via a context switch (how?) Process A Process B Exce p time

tion user code kernel code context switch user code kernel code context switch user code 38 Processes Spring 2016 Processes First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies 39 Processes Spring 2016

Creating New Processes & Programs fork-exec model (Linux): fork() creates a copy of the current process execve() replaces the current process code & address space with the code for a different program fork() and execve() are system calls Other system calls for process management: getpid() exit() wait() / waitpid() Process 2 Process 1 Memory Stack Heap Data Code fork() Memory Stack Heap Data Code

CPU CPU Registe rs Registe rs execve() Chrome.ex e 40 Processes Spring 2016 fork: Creating New Processes pid_t fork(void) Creates a new child process that is identical to the calling parent process, including all state (memory, registers, etc.) returns 0 to the child process returns childs process ID (pid) to the parent process Child is almost identical to parent: Child gets an identical pid_t pid = fork(); (but separate) copy of theif (pid == 0) { parents virtual address printf("hello from child\n"); space } else { printf("hello from parent\n");

Child has a different PID } than the parent fork is unique (and often confusing) because it is called once but returns twice 41 Processes Spring 2016 Understanding fork Process x (parent) pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } 42 Processes Spring 2016 Understanding fork Process x (parent) pid_t pid = fork(); if (pid == 0) {

printf("hello from child\n"); } else { printf("hello from parent\n"); } Process y (child) pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } 43 Processes Spring 2016 Understanding fork Process x (parent) Process y (child) pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) {

printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { pid = y printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { pid = 0 printf("hello from child\n"); } else { printf("hello from parent\n"); } 44 Processes Spring 2016 Understanding fork Process x (parent) Process y (child) pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); }

pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { pid = y printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { pid = 0 printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } pid_t pid = fork(); if (pid == 0) { printf("hello from child\n"); } else { printf("hello from parent\n"); } hello from parent Which one is first?hello from child 45

Processes Spring 2016 Fork Example Parent and child both run the same code Distinguish parent from child by return value from fork() Which process runs first after the fork() is undefined Could be parent, could be child! Start with same state, but each has a private copy Same variables, same call stack, same file descriptors, same register contents, same instruction pointer (%rip) 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); } 46 Processes Fork Example:

Spring 2016 What interleavings are possible? stdout 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); } 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); } 47 Processes Spring 2016

Fork Example void { 1. 2. 3. 4. 5. 6. 7. 8. } 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); Both processes continue/start execution at line 3 Child does not call fork! The instruction pointer points to the instruction after the call to fork, the instruction pointer is part of the state that is copied to the child Child has variable pid = 0, parent has pid = process ID of child Concurrent execution: Cant predict execution order of parent and child Duplicate but separate address space: both processes have a copy of x x has a value of 1 at line 3 in both parent and child

48 Processes Fork-Exec Spring 2016 Note: the return values of fork & execv should be checked for errors. fork-exec model: fork() creates a copy of the current process execve() replaces the current process code & address space with the code for a different program There is a whole family of exec calls see exec(3) and execve(2) // Example arguments: path="/usr/bin/ls", // argv[0]="/usr/bin/ls", argv[1]="-ahl", argv[2]=NULL void fork_exec(char * path, char * argv[]) { pid_t pid = fork(); if (pid != 0) { printf("Parent: created a child %d\n", pid); } else { printf("Child: about to exec a new program\n"); execv(path, argv); } printf("This line printed by parent only!\n"); } 49 Processes Spring 2016

Exec-ing a new program Stack Very high-level diagram of what happens when you run the command ls in a Linux shell: Heap Data Code: /usr/bin/bash fork(): child parent Stack child Stack Stack exec() Heap Heap Data Code: Data Code: /usr/bin/bash /usr/bin/bash

Data Code: /usr/bin/ls 50 Processes Spring 2016 execve Example Execute /usr/bin/ls l lab4 in child process using current environment: (argc == 3) myargv environ myargv[argc] = NULL myargv[2] myargv[1] myargv[0] envp[n] = NULL envp[n-1] envp[0] if ((pid = fork()) == 0) { lab4 -l /usr/bin/ls PWD=/homes/iws/rea/351 USER=rea /* Child runs program */ if (execve(myargv[0], myargv, environ) < 0) { printf("%s: Command not found.\n", myargv[0]);

exit(1); Run the printenv command in a Linux shell to see your own environment variables 51 Processes Structure of the stack when a new program starts Spring 2016 Null-terminated Bottom of stack environment variable strings Null-terminated command-line arg strings envp[n] == NULL envp[n-1] ... envp[0] argv[argc] = NULL argv[argc-1] ... argv (in %rsi) argv[0] argc (in %rdi) Stack frame for libc_start_main Future stack frame for

main environ (global var) envp (in %rdx) Top of stack 52 Processes Spring 2016 exit: Ending a process void exit(int status) Exits a process Status code: 0 is used for a normal exit, nonzero for abnormal exit atexit() registers functions to be executed upon exit void cleanup(void) { printf("cleaning up\n"); } void fork6() { atexit(cleanup); fork(); exit(0); } cleanup is a function pointer 53

Processes Spring 2016 Processes First some preliminaries Control flow Exceptional control flow Asynchronous exceptions (interrupts) Synchronous exceptions (traps & faults) Processes Creating new processes Fork and wait Zombies 54 Processes Spring 2016 Zombies Idea When process terminates, it still consumes system resources Various tables maintained by OS

Called a zombie A living corpse, half alive and half dead Reaping Performed by parent on terminated child Parent is given exit status information Kernel then deletes zombie child process What if parent doesnt reap? If any parent terminates without reaping a child, then the orphaned child will be reaped by init process (pid == 1) On more recent Linux systems, init has been renamed as systemd. But in long-running processes we need explicit reaping e.g., shells and servers 55 Processes Spring 2016 wait: Synchronizing with Children Parent reaps a child by calling the wait function int wait(int *child_status) Suspends current process (i.e. the parent) until one of its children terminates

Return value is the pid of the child process that terminated On successful return, the child process is reaped If child_status != NULL, then the int that it points to will be set to a value indicating why the child process terminated NULL is a macro for address 0, the null pointer There are special macros for interpreting this status see man wait(2) If parent process has multiple children, wait() will return when any of the children terminates waitpid can be used to wait on a specific child process 56 Processes Spring 2016 Modeling fork with Process Graphs A process graph is a useful tool for capturing the partial ordering of statements in a concurrent program: Each vertex is the execution of a statement

a -> b means a happens before b Edges can be labeled with current value of variables printf vertices can be labeled with output Each graph begins with a vertex with no inedges Any topological sort of the graph corresponds to a feasible total ordering. Total ordering of vertices where all edges point from left to right 57 Processes Spring 2016 wait: Synchronizing with Children void fork_wait() { int child_status; if (fork() == 0) { printf("HC: hello from child\n"); exit(0); } else { printf("HP: hello from parent\n"); wait(&child_status); printf("CT: child has terminated\n"); } printf("Bye\n"); } HC printf HP fork printf exit CT

Bye wait printf forks.c Feasible output: Infeasible output: HC HP HP CT CT Bye Bye HC 58 Processes Spring 2016 Process management summary fork gets us two copies of the same process But fork() returns different values to the two processes execve has a new process substitute itself for the one that called it Two-process program: First fork() if (pid == 0) { /* child code */ } else { /* parent code */ } Two different programs:

First fork() if (pid == 0) { execve() } else { /* parent code */ } Now running two completely different programs wait / waitpid used to synchronize parent/child execution and to reap child process 59 Processes Spring 2016 Summary Processes At any given time, system has multiple active processes On a one-CPU system, only one can execute at a time, but each process appears to have total control of the processor OS periodically context switches between active processes Implemented using exceptional control flow Process management fork: one call, two returns exec: one call, usually no return wait or waitpid: synchronization exit: one call, no return 60

Processes Spring 2016 Detailed examples 61 Processes Spring 2016 fork Example: Two consecutive forks Bye void fork2() { printf("L0\n"); fork(); printf("L1\n"); fork(); printf("Bye\n"); } printf L1 printf L0 printf Bye fork Bye L1 fork

printf Feasible output: L0 L1 Bye Bye L1 Bye Bye printf Bye printf fork printf Infeasible output: L0 Bye L1 Bye L1 Bye Bye 62 Processes Spring 2016 fork Example: Three consecutive forks Both parent and child can continue forking void fork3() {

printf("L0\n"); fork(); printf("L1\n"); fork(); printf("L2\n"); fork(); printf("Bye\n"); } L2 L1 L0 L1 Bye Bye L2 Bye Bye Bye Bye L2 Bye Bye L2 63 Processes Spring 2016 fork Example: Nested forks in

children void fork5() { printf("L0\n"); if (fork() == 0) { printf("L1\n"); if (fork() == 0) { printf("L2\n"); } } printf("Bye\n"); } L2 Bye printf printf L1 print f Bye L0 printf fork fork Bye printf printf Feasible output: L0 Bye L1 L2 Bye Bye

Infeasible output: L0 Bye L1 Bye Bye L2 64 Processes Zombie Exampl e Spring 2016 void fork7() { if (fork() == 0) { /* Child */ printf("Terminating Child, PID = %d\n", getpid()); exit(0); } else { printf("Running Parent, PID = %d\n", getpid()); while (1) ; /* Infinite loop */ } } forks.c linux> ./forks 7 & [1] 6639 Running Parent, PID = 6639 Terminating Child, PID = 6640 linux> ps

PID TTY TIME CMD 6585 ttyp9 00:00:00 tcsh 6639 ttyp9 00:00:03 forks 6640 ttyp9 00:00:00 forks 6641 ttyp9 00:00:00 ps linux> kill 6639 [1] Terminated linux> ps PID TTY TIME CMD 6585 ttyp9 00:00:00 tcsh 6642 ttyp9 00:00:00 ps ps shows child process as defunct Killing parent allows child to be reaped by init 65 Processes Nonterminating Child Example linux> ./forks 8 Terminating Parent, PID = 6675

Running Child, PID = 6676 linux> ps PID TTY TIME CMD 6585 ttyp9 00:00:00 tcsh 6676 ttyp9 00:00:06 forks 6677 ttyp9 00:00:00 ps linux> kill 6676 linux> ps PID TTY TIME CMD 6585 ttyp9 00:00:00 tcsh 6678 ttyp9 00:00:00 ps Spring 2016 void fork8() { if (fork() == 0) { /* Child */ printf("Running Child, PID = %d\n", getpid()); while (1) ; /* Infinite loop */ } else { printf("Terminating Parent, PID = %d\n", getpid()); exit(0); } } forks.c Child process still active even though parent has

terminated Must kill explicitly, or else will keep running indefinitely 66 Processes Spring 2016 wait() Example If multiple children completed, will take in arbitrary order Can use macros WIFEXITED and WEXITSTATUS to get information about exit status void fork10() { pid_t pid[N]; int i; int child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) exit(100+i); /* Child */ 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); } } 67 Processes

Spring 2016 waitpid(): Waiting for a Specific Process pid_t waitpid(pid_t pid, int &status, int options) suspends current process until specific process terminates various options (that we wont talk about) void fork11() { pid_t pid[N]; int i; int child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) exit(100+i); /* Child */ for (i = 0; i < N; i++) { pid_t wpid = waitpid(pid[i], &child_status, 0); 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); } } 68

Recently Viewed Presentations

  • Holy Name on the Throne - Chinese Immanuel Church

    Holy Name on the Throne - Chinese Immanuel Church

    尊榮歸我神 Ascribe Greatness WEST, MARY KIRKBRIDE & MARY LOU LOCKE & PETER 1979 INTEGRITYS HOSANNA! MUSIC CCLI #1133585 尊榮歸我神 Ascribe Greatness 但 願 尊 榮 歸 於 主 我 神 Ascribe greatness to our God, the Rock 他 作 為...
  • Universal Cell Phone Sound Amplifier

    Universal Cell Phone Sound Amplifier

    Take 10 minutes on your own to sketch 3 or more conceptual drawings of a universal cell phone sound amplifier. You will be sharing these with your team members, so please do not discuss during the time given for your...
  • #39Counting Atoms - Ms. Smart&#x27;s science

    #39Counting Atoms - Ms. Smart's science

    *Counting atoms. When counting atoms you must always remember the subscripts behind each element. H 2 O There are 2 H and 1 O atoms in H 2. OAlso, you must multiply the subscript by the coefficient in order to...
  • COS Standard 1 - Lee County School District

    COS Standard 1 - Lee County School District

    Interpreting the impact of change from workshop to factory on workers' lives , including the New Industrial Age from 1870-1900, afl-cio, iWW, the pullman strike, the haymarket square riot, and the impact of John d. rockefeller, andrew Carnegie, samuelgompers, eugene...
  • Integrated Full Text Search (iFTS) with SQL Server

    Integrated Full Text Search (iFTS) with SQL Server

    Instance level thesaurus. sys.sp_fulltext_load_thesaurus_file (lcid) Loads all the data specified in the Thesaurus XML corresponding to the language with specified . ... Total time is combining time to crawl and time of merge into index. Indexing Performance.
  • Prescribed Burning at Saint John&#x27;s

    Prescribed Burning at Saint John's

    Prescribed Burn Safety Only You Can Prevent an Accident Prescribed Burning at Saint John's Equipment Communication Tactics Safety Prescribed Burning at Saint John's Equipment Prescribed Burning at Saint John's Equipment Prescribed Burning at Saint John's Communication Prescribed Burning at Saint...
  • The provision of AC, DC & Telecommunications Services

    The provision of AC, DC & Telecommunications Services

    The Installation and Commissioning of MSAN's (Multi Service Access Nodes) and DSLAM's (Digital Subscriber Line Access Multiplexers. Fixed line and Mobile Telecommunications equipment. Copper, Co-axial, Cat 5/6 and fibre installations. Key Competencies
  • Talking About Voting

    Talking About Voting

    At the local level, have you ever wondered why the streets may be better in some parts of town than in others? If you look into it, you will almost always find that the areas with good streets are where...