w2 2 Post
w2 2 Post
w2 2 Post
Processes in C/Unix
Chapter 3 (R&R)
Process as Abstraction
• Talked about C programs a bit
Heap
Top-down: Why Processes?
The Birth of a Process: Executable
myprogram.c myprogram.o
int j; data
char* s = “hello\n”; assembler object
file
int p() {
j = write(1, s, 6);
return(j); data
}
…..
linker
libraries
p:
store this and
store that other
push objects
jsr _write
compiler ret
etc.
data
myprogram.s
program
myprogram
(executable file)
Unix Processes
• Process trees
• Creation: fork/exec
• Synchronization/Control: wait
• Termination: exit
• Error handling
• Identities
Processes in Unix
• Processes in Unix form a hierarchy
• Root is called systemd, started by OS
• Child is created by parent
• Relationship important for communication
Examples?
Switching:foreground to background
• <loop>
• ^z to suspend a process; get control back
• bg run it in the background
• fg run it in the foreground
y Program A fork++
y: fork
Data
R0
x Program B x: fork
Rn
Data
PC x => z=> y
registers
x == y 2n
address main memory
Example: Process Creation via Fork
#include <unistd.h> Fork returns twice. It returns a 0 PID to the child
int pid;
int status = 0; and the child’s PID to the parent
pid = fork ();
if (pid > 0) {
printf (“Parent: child has
pid=%d”, pid); Parent typically blocks or waits until the child
…
pid = waitpid(pid, &status, 0); terminates by using wait or waitpid
} else if (pid == 0) {
printf (“child here”);
… Child or any process can return an exit status
exit(status);
} else {
perror (“fork problem”); Always check for errors (-1) on syscalls
exit (-1);
Fork example
simplefork.c:
• simplefork.c
• simplechain.c
Waiting
Called by parent to wait (block) until child exits
#include <sys/wait.h>
pid_t wait (int *stat_loc); // any child
pid_t waitpid (pid_t pid, int *stat_loc,
int options); // spec. child
childpid = fork();
if (childpid == 0) { /* child code */
print i; //#1
i = 7;
print i; //#2
}
else {
print i; // #3 /* parent code */
i = 3;
print i; // #4
wait (NULL);
print i; // #5
}
Top-down:Why Processes?
• Why we need fork? Multi-tab browser.
// implementation of make
foo.o: foo.h foo.c
gcc foo.c
cp foo.o /usr/bin/foo.o
…
execl
int execl (const char *path,
const char *arg0, // strings
const char *arg1, …
(char *) 0);
fork fork
parent child
exec
initialize
child
context
wait exit
Process Termination
• How does a process terminate?
• Return from main
• Falls off the end of main
• Call exit
• Call abort
• Receives a death signal or exception
kill (pid_t pid, SIGKILL)
Process Termination (cont’d)
• Should be orderly
• Child terminates before parent and parent is
waiting