Tanja Meeren Tanja Meeren - 1 month ago 11
C Question

Flow of the fork, how many forks do I have?

I have executed this code.
I know that the orders of the messages are in any order (because i explicitly did not use semaphores)
How does the flow of my program look and why?

The parent is executed so "baz" is printed once. Can somebody explain why "bar" is not printed? Why do I get "foo" (the if statement is true) two times and not one or three times(not that i want this but i want to understand the logic)(because a colleague says that i should get three times foo out of it)?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
int p;
p = fork();
if (fork()==0) {
if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) {
fork();
}
printf("bar\n");
}
else {
if (p!=0) execl("/bin/echo", "/bin/echo", "baz", 0);
}
}

Answer

execl does not return, it replaces the entire process image with /bin/echo. There are therefore zero "bar"s.

    if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) {
      fork();
    }
    /* Not reached if execl succeeded.
    Because the exec family of functions replace the process image with
    another executable.  Flow will never return, unless there is an
    error. */
    printf("bar\n");

There are two "foo"s.

  int p;
  p = fork();
  /* Two processes now */
  if (fork()==0) {
      /* Two child processes here. */
      execl("/bin/echo", "/bin/echo", "foo", 0); /* (Simplification) */
      /* Two (/bin/echo foo) here, flow will never return back */
  }

There is one "baz".

int p;
p = fork();
/* if block removed for simplicity */
if (p != 0)
{
    /* Only the initial parent process. */
    execl("/bin/echo", "/bin/echo", "baz", 0);
}
Comments