Professional Documents
Culture Documents
Lecture 9
Fork and Exec
Read Ch 4.4 - 4.5
4.1
Process Creation
Parent
Child Child
4.2
The fork( ) command
4.3
Using fork( )
Example:
Demo 1
4.4
Diagram of fork( )
4.5
Distinguishing Parent and Child
cpid = fork( );
if (cpid == 0) {
//child code
} else {
//parent code
}
Demo 2
4.6
Multiple forks
What is the output of the following code?
4.7
Diagram of two process code
4.8
Distinguishing the grandchild from the
child
Question: How do you distinguish the grandchild from the child?
We will write this code in class.
4.9
Multiple forks from the parent only
4.10
The exec( ) function
4.11
Properties of the exec( ) call
4.12
Example with execlp( )
int main(void) {
int cpid;
cpid = fork( );
if (cpid == 0) { //child
execlp( "ls", "ls", "-l", NULL);
} else {
cout << "I am the parent." << endl;
}
return 0;
}
Demo 4
4.13
Process synchronization
The parent can wait for a child to terminate using the wait( )
function.
int cpid_done, status;
cpid_done = wait(&status);
The caller sleeps until any child terminates.
cpid_done gets the pid of the child that terminated.
status gets the exit status of the terminated process.
4.14
Process Termination
4.15
Typical code using fork, exec and wait
4.16
Basic Shell code
4.17