fork, exec and wait
Creating a process with fork, making it run another program with exec, waiting for it with wait and its status, and knowing what becomes of orphans and zombies: predicting what each process prints.
- 34 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- The steps
- Scenarios
A few cards from the deck
fork: what is it?
Show the answer
The system call that creates a new process, a copy of the calling one, and returns 0 in the copy, the copy's number in the original, and -1 on failure.
Both processes resume at the line after the call; only the returned value tells them apart, hence the
if (pid == 0)that separates the child's code from the parent's.What does this program print?
```c
int main(void) {
int x = 5;
pid_t p = fork();
if (p == 0) {
x = x + 1;
return 0;
}
wait(NULL);
printf("%d\n", x);
return 0;
}`565puis611
Show the answer
5The child works on a copy of
x: itsx = x + 1does not touch the parent's variable, which still prints 5. For a child to pass a value back you need an exit code, a pipe or shared memory.After
fork, the returned value is … in the child and, in the parent, the ….Show the answer
After
fork, the returned value is 0 in the child and, in the parent, the child's process number.The parent needs the child's number to wait for it or signal it; the child finds its own with
getpid()and its parent's withgetppid().The exec family: what is it?
Show the answer
System calls (
execl,execlp,execv,execvp...) that replace the calling process's program with another one, without creating a new process.The process number stays the same, but code, heap and stack are replaced: if the call succeeds it never returns, and the next line runs only if it failed.
A shell runs the ls command: which step comes after "The shell calls fork"?
- The child calls execvp("ls") and becomes ls
- ls prints its output then calls exit
- The shell's waitpid returns the child's status
- The shell shows the prompt again
Show the answer
The child calls execvp("ls") and becomes ls
The shell cannot call
execitself, it would be replaced byls. It therefore creates an expendable child, stays blocked inwaitpidwhilelsruns, and collects its status, which also avoids the zombie.