0

I came across a stripped down shell program in Tannenbaum's book on MINIX.

while(1) {
 read_command(command, parameters);
 if (fork() != 0) 
      wait(&status);    /* parent code */
 }
 else {
      execve(command, parameters, 0);  /* child code */
 }
}

When the infinite loop executes its first iteration, fork() will return 0 indicating it created a child process, when it executes the second time, wont fork() create a new child process ? How wait(&status) will ever execute?

I am new to understanding how an OS works/is built.

Thanks!

1 Answers1

1

fork creates a new process immediately, so both processes see fork return, but with different return values. In the parent, the return value is the non-zero process ID of the child, so the parent executes wait. In the child, fork returns 0, so the child executes execve.

chepner
  • 497,756
  • 71
  • 530
  • 681