无法理解代码的输出

标签 c process waitpid

我编写了以下代码并运行了几次。但每次结果都不一样。

#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 表示当前正在运行子进程。
  3. >0 表示当前正在运行父进程。

因此父进程根据命令行参数的数量来 fork 子进程。然后等待每个连续的子进程退出。

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

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

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

的返回值

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

这是一对示例 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]

关于无法理解代码的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818373/

相关文章:

c - int 与 char[2] 错误的间接级别不同

c - 获取 ipaddress 的值

variables - VHDL:变量和过程

c - WSTOPSIG(状态) == 22 & WTERMSIG(状态) == 9;这些数字从何而来?

c++ - 运行后台进程 linux 简单 shell。 C++

c - 使用 C 中的缓冲区和多线程从文本文件读取

检查数组是否包含 C 中另一个数组的所有数组值

python - 无法从正在运行的进程读取标准输出

运行脚本后 pythonw.exe 进程不退出

c - getpid(), WIFSHSTOPPED(state) 检查子进程是否处于 sleep 状态