fork in a for loop

示例代码如下

#include <stdio.h>

void main()
{
   int i;

   for (i=0;i<3;i++)
   {
      fork();

      // This printf statement is for debugging purposes
      // getppid(): gets the parent process-id
      // getpid(): get child process-id

      printf("[%d] [%d] i=%dn", getppid(), getpid(), i);
   }

   printf("[%d] [%d] hin", getppid(), getpid());
}

what happends

  • Loop starts in parent, i == 0.

  • Parent fork()s, creating child 1.

  • You now have two processes. Both print i=0.

  • Loop restarts in both processes, now i == 1.

  • Parent and child 1 fork(), creating children 2 and 3.

  • You now have four processes. All four print i=1.

  • Loop restarts in all four processes, now i == 2.

  • Parent and children 1 through 3 all fork(), creating children 4 through 7.

  • You now have eight processes. All eight print i=2.

  • Loop restarts in all eight processes, now i == 3.

  • Loop terminates in all eight processes, as i < 3 is no longer true.

  • All eight processes print hi.

  • All eight processes terminate.

0 printed two times, 1 printed four times, 2 printed 8 times, and hi printed 8 times.

思考

如果在 for loop 中调用 fork 的行为是这样的,那么以示例代码为例,怎么样让一个父进程只启动三个活跃(示例中能调用 printf)的子进程呢?

结合上面的分析,需要在 for loop 中对 fork 的返回值做特殊处理,具体做法如下

for (i = 0; i < 3; i++)
{
	pid_t pid = fork();

	if (0 == pid || -1 == pid)
		break;

	// This printf statement is for debugging purposes
	// getppid(): gets the parent process-id
	// getpid(): get child process-id
	printf("[%d] [%d] i=%dn", getppid(), getpid(), i);
}