SLIDE 2 After calling fork()
void f (int x) { int z; fork(); } void g() { char a; int i; f (42); } int main () { g(); return 0; } RET addr 1 RET addr 2 Location 3
RET addr 1 a i 42 RET addr 2 z
SP
Stack for new Process
Child SP
RET addr 1 a i 42 RET addr 2 z Stack for Boot Process
Example: Race Conditions
#include <iostream> #include <unistd.h> #include <sys/types.h> int main() { pid_t pid; if ((pid = fork()) < 0 ) exit(1); //error if(pid != 0) { for(int i = 0; i < 100; i++) cout<<"Parent process "<< i <<endl; } else { for(int i = 100; i < 200; i++) cout <<"Child process "<< i << endl; } return 0; }
Process Termination Bach 7.3
– Executing a return from the main function. – Calling the exit function. (ANSI C) – Calling the _exit function. (Sys call)
– When a process receives certain signals.
Normal Process Termination
– Status: IPC. – NEVER returns.
– Mask Signals. – Close open files. – Release memory. – Save the process exit status. – Set the process state to ZOMBIE.
#include <stdlib.h> void exit (int status);
Awaiting Process Termination Bach 7.4
#include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status);
– Returns the PID of a zombie child -1 when no children exist. – Status is the exit status of the child process. – Wait can block the caller until a child process terminates.
– Search for a zombie child of the process. – Extract PID and status of the zombie child. – Release the process table slot.
Orphans and Zombies
- When a child exits when its parent is not
currently executing a wait(), a zombie emerges.
– A zombie is not really a process as it has terminated but the system retains an entry in the process table. – A zombie is put to rest when the parent finally executes a wait().
- A child process whose parent has terminated
is referred to as orphan.
- When a parent terminates, orphans and
zombies are adopted by the init process (prosess-id:0) of the system.