class15 processes
DESCRIPTION
linuxTRANSCRIPT
-
7/18/2019 Class15 Processes
1/25
Processes
TopicsTopics Process context switches
Creating and destroying processes
cs105
CS 105Tour of the Black Holes of Computing!
-
7/18/2019 Class15 Processes
2/25
2 CS 105
ProcessesDef: ADef: Aprocessprocessis an instance of a running program.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 keyProcess provides each program with two keyabstractions:abstractions:
Logical control flowEach program seems to have exclusive use of the CPU.
Private address spaceEach program seems to have exclusive use of main memory.
How are these illusions maintained?How are these illusions maintained? Process executions interleaved (multitasking)
Address spaces managed by virtual memory system
-
7/18/2019 Class15 Processes
3/25
3 CS 105
Logical Control Flows
Time
Process A Process B Process C
Each process has its own logical control flow
-
7/18/2019 Class15 Processes
4/25
4 CS 105
Concurrent Processes
Two processesTwo processesrun concurrentlyrun concurrently((are concurrent)are concurrent)if theirif theirflows overlap in time.flows overlap in time.
Otherwise, they areOtherwise, they aresequential.sequential.
Examples:Examples: Concurrent: A & B, A & C
Sequential: B & C
Time
Process A Process B Process C
-
7/18/2019 Class15 Processes
5/25
5 CS 105
User View: Concurrent Processes
Control flows for concurrent processes are physicallyControl flows for concurrent processes are physicallydisjoint in time. (Except on multi-CPU machines.)disjoint in time. (Except on multi-CPU machines.)
However, we can think of concurrent processes asHowever, we can think of concurrent processes asrunning in parallel with each other.running in parallel with each other.
Time
Process A Process B Process C
-
7/18/2019 Class15 Processes
6/25
6 CS 105
Context Switching
Processes are managed by a shared chunk of OS codeProcesses are managed by a shared chunk of OS code
called thecalled thekernelkernel Important: the kernel is not a separate process, but ratherruns as part of (or on behalf of) some user process
Control flow passes from one process to another via aControl flow passes from one process to another via a
context switchcontext switchProcess Acode
Process Bcode
user code
kernel code
user code
kernel code
user code
Time
context switch
context switch
-
7/18/2019 Class15 Processes
7/25
7 CS 105
Private Address Spaces
Each process has its own private address space.Each process has its own private address space.
kernel virtual memory(code, data, heap, stack)
memory mapped region forshared libraries
run-time heap(managed by malloc)
user stack(created at runtime)
unused0
%esp (stack pointer)
memoryinvisible touser code
brk
0xc0000000
0x08048000
0x40000000
read/write segment(.data, .bss)
read-only segment(.init, .text, .rodata)
loaded from theexecutable file
0xffffffff
-
7/18/2019 Class15 Processes
8/25
8 CS 105
fork: Creating New Processes
int fork(void)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 childspidto 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
oncebut returnstwice
Huh? Run thatby me again!
-
7/18/2019 Class15 Processes
9/25
9 CS 105
Fork Example #1
void fork1(){ int x = 1; // arent and child !ill et private copies# pid$t pid = fork(); if (pid == 0) {
printf("%hild has x = &d\n"' x); } else {
printf("arent has x = &d\n"' x); } printf("*+e from process &d !ith x = &d\n"' etpid()' x);}
Key PointsKey Points
Parent and child both run same codeDistinguish parent from child by return value fromfork
Start with same state, but each has private copyIncluding shared input and output file descriptors
Relative ordering of their print statementsundefined
-
7/18/2019 Class15 Processes
10/25
10 CS 105
Fork Example #2
void fork,(){ printf("-0\n"); fork(); printf("-1\n");
fork(); printf("*+e\n");}
Key PointsKey Points Both parent and child can continue forking
-0 -1
-1
*+e*+e
*+e
*+e
-
7/18/2019 Class15 Processes
11/25
11 CS 105
Fork Example #3
void fork.(){ printf("-0\n");
fork(); printf("-1\n");
fork(); printf("-,\n");
fork(); printf("*+e\n");
}
Key PointsKey Points Both parent and child can continue forking
-1 -,
-,
*+e*+e
*+e
*+e
-1 -,
-,
*+e
*+e*+e
*+e
-0
-
7/18/2019 Class15 Processes
12/25
12 CS 105
Fork Example #4
void fork(){ printf("-0\n");
if (fork() #= 0) {printf("-1\n");if (fork() #= 0) { printf("-,\n"); fork();}
} printf("*+e\n");}
Key PointsKey Points Both parent and child can continue forking
-0 -1
*+e
-,
*+e
*+e
*+e
-
7/18/2019 Class15 Processes
13/25
13 CS 105
Fork Example #5
void fork5(){ printf("-0\n");
if (fork() == 0) {printf("-1\n");if (fork() == 0) { printf("-,\n"); fork();}
} printf("*+e\n");}
Key PointsKey Points Both parent and child can continue forking
-0 *+e
-1
*+e
*+e
*+e
-,
-
7/18/2019 Class15 Processes
14/25
14 CS 105
exit: Destroying Process
void exit(int stats)void exit(int stats) Exits a process
Normally return with status 0 (success)
atexit()registers functions to be executed upon exit
void cleanp(void) { printf("cleanin p\n");}
void fork() { atexit(cleanp);
fork(); exit(0);}
-
7/18/2019 Class15 Processes
15/25
15 CS 105
Zombies
IdeaIdea
When process terminates, still consumes system resourcesVarious tables maintained by OS (to store exit status)
Called a zombieLiving corpse, half alive and half dead
ReapingReaping Performed by parent on terminated child
Parent is given exit status information
Kernel discards process
What If Parent Doesnt Reap?What If Parent Doesnt Reap? If any parent terminates without reaping a child, then child
will be reaped byinitprocess
Only need explicit reaping for long-running processesE.g., shells and servers
-
7/18/2019 Class15 Processes
16/25
16 CS 105
linx2 ./forks 7 &314 .6nnin arent' 78 = .9erminatin %hild' 78 = 0linx2ps 78 99: 97< %855 tt+p 00>00>00 tcsh. tt+p 00>00>0. forks0 tt+p 00>00>00 forks ?defnct2
1 tt+p 00>00>00 pslinx2kill 6639314 9erminatedlinx2ps 78 99: 97< %855 tt+p 00>00>00 tcsh, tt+p 00>00>00 ps
Zombie Example
psshows childprocess as defunct
Killing parent allowschild to be reaped
void fork@(){
if (fork() == 0) {/A %hild A/printf("9erminatin %hild' 78 = &d\n"' etpid());exit(0);
} else {printf("6nnin arent' 78 = &d\n"' etpid());
!hile (1) ; /A 7nfinite loop A/
}}
-
7/18/2019 Class15 Processes
17/25
17 CS 105
linx2 ./forks 89erminatin arent' 78 = @56nnin %hild' 78 = @linx2ps 78 99: 97< %855 tt+p 00>00>00 tcsh@ tt+p 00>00>0 forks@@ tt+p 00>00>00 ps
linux>kill @linux>ps 78 99: 97< %855 tt+p 00>00>00 tcsh@ tt+p 00>00>00 ps
NonterminatingChild
Example
Child process still active
even though parent has
terminated
Must kill explicitly, or elsewill keep running
indefinitely
void fork(){ if (fork() == 0) {
/A %hild A/printf("6nnin %hild' 78 = &d\n"'
etpid());!hile (1) ; /A 7nfinite loop A/
} else {printf("9erminatin arent' 78 = &d\n"' etpid());exit(0);
}}
-
7/18/2019 Class15 Processes
18/25
18 CS 105
!ait: Synchronizing With Children
int !ait(int Achild$stats)int !ait(int Achild$stats)
Suspends current process until one of its childrenterminates
Return value ispidof child process that terminated
Ifchild$stats#= BC--, then integer it points to will beset to indicate why child terminated
-
7/18/2019 Class15 Processes
19/25
19 CS 105
!ait: Synchronizing WithChildrenvoid fork() {
int child$stats;
if (fork() == 0) { printf("D%> hello from child\n"); } else { printf("D> hello from parent\n"); !ait(Echild$stats); printf("%9> child has terminated\n"); } printf("*+e\n");
exit(0);}D
D% *+e
%9 *+e
-
7/18/2019 Class15 Processes
20/25
20 CS 105
Wait Example If multiple children completed, will take in arbitrary order
Can use macros WIFEXITED and WEXITSTATUS to getinformation about exit status
void fork10(){ pid$t pid3B4; int i;
int child$stats; for (i = 0; i ? B; i)
if ((pid3i4 = fork()) == 0) exit(100i); /A %hild A/
for (i = 0; i ? B; i) {pid$t !pid = !ait(Echild$stats);
if (F7G
-
7/18/2019 Class15 Processes
21/25
21 CS 105
Waitpid!aitpid(pid' Estats' options)
Can wait for specific process
Various options available (see man page)
void fork11(){ pid$t pid3B4; int i;
int child$stats; for (i = 0; i ? B; i)
if ((pid3i4 = fork()) == 0) exit(100i); /A %hild A/
for (i = 0; i ? B; i) {pid$t !pid = !aitpid(pid3i4' Echild$stats' 0);
if (F7G
-
7/18/2019 Class15 Processes
22/25
22 CS 105
Wait/Waitpid Example Outputs
%hild .55 terminated !ith exit stats 10.%hild .5 terminated !ith exit stats 10,%hild .5. terminated !ith exit stats 101%hild .5, terminated !ith exit stats 100%hild .5 terminated !ith exit stats 10
%hild .5 terminated !ith exit stats 100
%hild .5 terminated !ith exit stats 101%hild .5@0 terminated !ith exit stats 10,%hild .5@1 terminated !ith exit stats 10.%hild .5@, terminated !ith exit stats 10
Using!ait (fork10)
Using!aitpid (fork11)
-
7/18/2019 Class15 Processes
23/25
23 CS 105
exec: Running New Programsint execl(char Apath' char Aar0' char Aar1' L' 0)int execl(char Apath' char Aar0' char Aar1' L' 0)
Loads and runs executable atpathwith argsar0,ar1, pathis the complete path of an executablear0becomes the name of the process
Typicallyar0is either identical topath, or else it contains only theexecutable filename frompath
Real arguments to the executable start withar1, etc.
List of args is terminated by a(char A)0argument
Returns1if error, otherwise doesnt return!
main() { if (fork() == 0) {
execl("/sr/Kin/cp"' "cp"' "foo"' "Kar"' BC--); } !ait(BC--); printf("cop+ completed\n"); exit(0);}
-
7/18/2019 Class15 Processes
24/25
24 CS 105
Summarizing
ProcessesProcesses At any given time, system has multiple active processes
But only one (per CPU core) can execute at a time
Each process appears to have total control of processor +
private memory space
-
7/18/2019 Class15 Processes
25/25
25 CS 105
Summarizing (cont.)
Spawning ProcessesSpawning Processes
Call toforkOne call, two returns
Terminating ProcessesTerminating Processes Callexit
One call, no return
Reaping ProcessesReaping Processes Call!aitor!aitpid
Replacing Program Executed by ProcessReplacing Program Executed by Process Callexecl (or variant)
One call, (normally) no return