Unix fork() 系统调用

发布于 2024-12-23 13:53:09 字数 1095 浏览 1 评论 0原文

大家好,

我对 fork() 感到困惑。 fork() 是分叉子进程还是仅分叉父进程?

请帮助一些例子,

#include <unistd.h>
#include <stdio.h>

int main() {
  if (fork()) {
    fork();
    printf(" X\n");
  }
  return 0;
}

我想如何构建流程:

    parent
      |
   /    \
Parent  Child

所以输出将是

  X X X

另一个例子,

#include <unistd.h>
#include <stdio.h>

int main() {
  fork();
  fork();
  fork();

  printf(" X \n");

  return 0;
}

图表会是这样的吗?

                 Fork start
                    /     \
                Parent    Child        1st fork done output 2 of X
                /  \      /   \
              P     C    P    C        2nd fork done output 4 of X
            / \    / \  /\    /\
           P  C   P  C P  C  P  C      3rd fork done output 8 of X

另一个问题是我该如何画画

if (fork() || fork() || fork())
  fork();

,或者

if (fork() && fork())
  fork();

如果有人纠正我,我会很高兴。

Good daytime to all

I am confused with fork(). Does fork() forks child process or only parent?

please help on some examples

#include <unistd.h>
#include <stdio.h>

int main() {
  if (fork()) {
    fork();
    printf(" X\n");
  }
  return 0;
}

is this how i suppose to build the processes:

    parent
      |
   /    \
Parent  Child

so the output would be

  X X X

another example is

#include <unistd.h>
#include <stdio.h>

int main() {
  fork();
  fork();
  fork();

  printf(" X \n");

  return 0;
}

the graph would be like this?

                 Fork start
                    /     \
                Parent    Child        1st fork done output 2 of X
                /  \      /   \
              P     C    P    C        2nd fork done output 4 of X
            / \    / \  /\    /\
           P  C   P  C P  C  P  C      3rd fork done output 8 of X

another question how can I draw

if (fork() || fork() || fork())
  fork();

or

if (fork() && fork())
  fork();

I would be glad if someone correct me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不放开 2024-12-30 13:53:09

fork 不会“创建父进程和子进程”,不。它创建当前进程的副本(副本是子进程,当前进程是父进程)。区别是根据fork返回值来完成的。

fork doesn't "create parent and child process", no. It creates a copy of the current process (the copy being the child and the current process being the parent). The distinction is done based on the fork return value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文