最大的问题是你孩子的代码:
if (pid == 0) { .... }
属于父代码的同一个循环(就在右边):
if (pid != 0) { .... }
此外,您永远不会检查pid == -1
(fork()
失败).
写这样的更标准的方法是:
switch (pid = fork()) { case -1: /* handle fork error */ exit(1); case 0: /* child code goes here */ _exit(0); default: /* parent code goes here */ } /* Also you probably want to look into the `wait()` syscall. */ do {} while (wait(NULL) != -1); /* <--- the very minimum */