Agenda For Today
Agenda For Today
Resource sharing
Parent and children share all resources.
Parent and child share no resources.
Execution
Parent and children execute concurrently.
Parent waits until children terminate.
Process Creation …
Address space
Child duplicate of parent.
Child has a program loaded onto it.
UNIX examples
fork system call creates a new process
exec system call used after a fork to replace the
process’ memory image with a new executable.
Processes Tree on a UNIX
System
fork()
When the fork system call is executed, a new
process is created which consists of a copy of the
address space of the parent.
The return code for fork is zero for the child process
and the process identifier of child is returned to the
parent process.
On success, both processes continue execution at
the instruction after the fork call.
On failure, -1 is returned to the parent process and
errno is set appropriately to indicate the reason of
failure; no child is created
What’s Happening at Process Creation?
The OS:
◦ Assigns a unique process identifier
◦ Allocates space for the process
◦ Initializes process control block
fork()—Sample Code
main()
{
int pid; Parent Process pid = 1234
...
pid = fork();
if (pid == 0) {
Child Process pid = 0
/* Code for child */
...
}
else {
/* Code for parent */
...
} Kernel Space
...
}
fork()—Inherits from the
Parent
The child process inherits the following attributes
from the parent:
Memory
Stack
Current working directory
Root directory
Open file descriptor table
Signal handling settings
Nice value
Etc.
fork()—Child Differs from
the Parent
The child process differs from the parent process:
Different process ID (PID)
Different parent process ID (PPID)
Child has its own copy of parent’s file descriptors
Etc.
fork()—Reasons for Failure
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1);
}
Sample Code—fork
if(pid == 0) { /* Child */
printf(“Child here!\n”);
exit(0);
}
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0);
}
}
Semantics of fork
fork
P
exec()
Typically the exec system call is used after a fork
system call by one of the two processes to replace
the process’ memory space with a new executable
program.
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1);
}
Sample Code—fork and
exec
if(pid == 0) { /* Child */
if (execlp(“/bin/ls”, “ls”, NULL)< 0) {
printf(“exec failed\n”);
exit(1);
}
}
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0);
}
}
Semantics of fork
parent parent parent
P P P
fork
P P ls ls
exec
child child child
1 2 3