Lecture Slides 08 082-Processes-Creating
Lecture Slides 08 082-Processes-Creating
Section 8: Processes
What is a process
Creating processes
Fork-Exec
Processes
University of Washington
Processes
University of Washington
Processes
University of Washington
Understanding fork
Process n Child Process m
pid_t pid = fork(); pid_t pid = fork();
if (pid == 0) { if (pid == 0) {
printf("hello from child\n"); printf("hello from child\n");
} else { } else {
printf("hello from parent\n"); printf("hello from parent\n");
} }
Fork Example
Parent and child both run the same code
Distinguish parent from child by return value from fork()
Which runs first after the fork() is undefined
Start with same state, but each has a private copy
Same variables, same call stack, same file descriptors…
void fork1()
{
int x = 1;
pid_t pid = fork();
if (pid == 0) {
printf("Child has x = %d\n", ++x);
} else {
printf("Parent has x = %d\n", --x);
}
printf("Bye from process %d with x = %d\n", getpid(), x);
}
Processes