无法理解代码的输出

Could not understand the output from the code

我写了下面的代码,运行 写了几次。但是每次结果都不一样

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
  pid_t id;
  int status; 
  while (--argc && (id=fork())) {
    waitpid(id,&status,0); /* Wait for child*/
  }
  printf("%d:%s\n", argc, argv[argc]);
  return 0;
}

我运行喜欢:

./a.out 1 2 3

然后有时我得到:

3: 3
2: 2
1: 1
0: ./a.out
$ 0: ./a.out  (It seems still running, waiting for my input)

有时我得到:

3: 3
$ 3: 3 (It seems still running, waiting for my input)

有什么想法吗?谢谢!

函数:fork()可以将pid设置为三种不同含义中的任何一种:

  1. -1表示发生错误。
  2. =0 表示当前 运行 child 进程。
  3. >0 表示当前 运行 parent 进程。

所以parent根据命令行参数的个数分叉children。然后等待每个连续的 child 退出。

每个child进程执行printf()函数然后退出

最后 parent 执行 printf() 函数,argc 为 0

注意:代码应该检查调用 waitpid()

的返回值

注意:代码应检查变量 id > 0 以确保对 fork() 的调用成功。实际上,该调用失败(返回 -1)将导致对 waitpid() 的调用永远等待,因为没有 child 进程等待 .

这是一对示例 rund,其中 untitled1 是可执行文件的名称

rkwill@richard-desktop:~/Documents/forum$ ./untitled1 1 2 3
3:3
2:2
1:1
0:./untitled1
rkwill@richard-desktop:~/Documents/forum$ ./untitled1 
0:./untitled1
rkwill@richard-desktop:~/Documents/forum$ 

从上面可以看出,当给定参数时,它会倒序列出它们,然后列出argv[0]

当没有参数时,它仍然列出 argv[0]