c - fork() 执行不同的进程

标签 c unix fork task children

我正在尝试使用多个 fork() 调用来创建多个具有不同任务的子级 我找到了一个代码 Multiple child process

这与我想要的非常接近,但我无法完全理解它

pid_t firstChild, secondChild;
firstChild = fork();
if(firstChild != 0)
{
  // In parent
  secondChild = fork();
  if(secondChild != 0)
  {
    // In parent
  }
  else
  {
    // In secondChild
  }
}
else
{
  // In firstChild
}

我的问题是:

  • 已创建多少个进程(我假设我们有 4 个进程,因为它是 2 个 fork !)?
  • 在这部分代码

firstChild = fork();
if(firstChild != 0)
{
    // In parent
    secondChild = fork();
    if(secondChild != 0)
    {
        // In parent
    }

“//在父进程中”是否意味着它们都是同一个进程(当我尝试测试它们时,它们具有相同的 PID)。

  • 如何使用 2 个 fork 创建 3 个子节点?(我可以画出一棵以 4 个叶子结尾的树,其中 3 个为子节点,1 个为父节点)

谢谢(如果我没有完全理解 Fork 概念,请随时告诉我)

最佳答案

How many process have been created (I assume that we have 4 since it's 2 forks!)?

根据您的 fork 结果,它应该是 0 到 2。如果没有出现问题,可能是 2。有一个父进程派生了 2 个子进程。

Does "//in parent" mean both of them are the same process (they have the same PID when I tried to test it).

是的。在您的情况下,代码正在检查 fork 的返回值是否非零。这不是一个好主意,因为它涵盖了两种不同的情况:

  • 它可能小于零,表示有错误,或者...
  • 它可以大于零,向父进程指示新生成进程的 pid 无论如何......考虑到一切顺利并且两个 fork 都成功,您最终将得到一个具有 2 个不同子进程的父进程。

How can I create 3 children using 2 forks?( I can draw the tree that ends with 4 leaves 3 of them are children and 1 parent

像这样的事情应该可以解决问题:

firstChild = fork();
if (firstChild < 0) {
    exit(EXIT_FAILURE);
    perror("fork");
}
secondChild = fork();

请注意,通过不再检查 fork() 的返回值,我会得到一个子进程在与父进程相同的位置继续执行。因此,下一个 fork 实际上将由父进程和子进程执行,每个进程都会生成一个新进程。所以我会得到这样的东西......

parent─┬─child1───(child1's child)
       └─child2

我想不出有什么方法可以只用 2 个 fork 就可以得到这个:

parent─┬─child1
       ├─child3
       └─child2

注意:按照 stackoverflow 的惯例,每个主题只能回答一个问题。

关于c - fork() 执行不同的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28739238/

相关文章:

c - C strcpy 的奇怪行为

c - 数组和字符的问题

sockets - 我可以测试文件描述符的类型是否适合 read() 吗?

linux - 在 fork 之前或之后对磁盘文件调用 mmap() 有什么区别?

C++ 删除具有有效地址的指针

c - A5/1安全算法3

c - 如何使用 1 个循环在 C 中打印等边三角形?

c - 使用 NPAPI 显示 SWF 文件(在 Xlib 上)

C - 程序中的 UNIX 命令

Perl-在fork/exec上传递一个开放的套接字