Sam
Sam

Reputation: 972

Why do my program with many forks not stop?

The Program which has many forks as below did not finish.

#include <unistd.h>
#include <iostream>

int main() { 
  static int fork_cnt = 0;
  const unsigned kCnt = 4;

  for (int i = 0; i < kCnt; ++i) {
    fork();
  }
  std::cout << "fork_cnt=" << fork_cnt << std::endl;
  return 0;
}

When I ran it, It stop as below. It seems that The main fork is finished, but other program is waitting for something.

fork_cnt=0
qingfeng@ubuntu:~$ fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
fork_cnt=0
...

Upvotes: 0

Views: 55

Answers (1)

Paul Kertscher
Paul Kertscher

Reputation: 9742

Actually the program is not waiting for anything. What happens here is that you create child processes, that detach from your current stdin (at least I believe they do given their behavior). When your original process returns, sh regains the control over your stdin and prompts you for input - hence the qingfeng@ubuntu:~$ in the second line of your second listing. Anyway, your child processes keep writing to stdout, therefor the fork_cnt=0are output after the qingfeng@ubuntu:~$. When all processes have ended sh sees no reason for prompting you again for an input, therefor it seems to you as if the program's still running, but if you entered some command (or just hit Enter) you'd see it did.

To test this, please try the following: Create an infinite loop in each child process right after its creation.

#include <unistd.h>
#include <iostream>

int main() { 
  static int fork_cnt = 0;
  const unsigned kCnt = 4;

  for (int i = 0; i < kCnt; ++i) {
    int pid = fork();
    while(pid == 0);
  }
  std::cout << "fork_cnt=" << fork_cnt << std::endl;
  return 0;
}

Now fork_cnt=0 is output only once and you regain the control over the terminal.

paul@www:~/Programming/playground/fork# ./a.out
fork_cnt=0
paul@www:~/Programming/playground/fork#

Anyway, the child processes are still running, which you can easily verify by entering ps in your shell.

Upvotes: 1

Related Questions