【问题标题】:Making a tree structure using forking in C在 C 中使用分叉创建树结构
【发布时间】:2014-03-05 23:03:17
【问题描述】:

我已经坚持了好几天了。我必须使用 fork() 函数编写以下树结构。有什么建议?这是我目前所拥有的:

代码:

   #include <stdio.h>
   #include <stdlib.h>
   main ()
   {
  int pid;
  pid = fork();
  //Child
  if (pid == 0){
  if ((pid = fork()) == 0)
  {
  printf("GrandChild: child pid = % d, my pid = %d, parent pid = %d \n",
                      pid, getpid(), getppid());
  }
  }
  exit(0); }

树形结构:

         A
   B           C
D            E   F

【问题讨论】:

  • 到目前为止,您编写了什么代码?
  • 对不起,我赶时间了。我现在添加了代码。
  • 请花时间正确格式化您的代码。
  • 另外,进一步解释您要解决的问题,因为树结构不太清楚。
  • B 和 C 是 A 的孩子,D 是 B 的左孩子,E 和 F 是 C 的孩子。

标签: c tree fork


【解决方案1】:

以下代码应创建您想要的树结构。每个进程派生出它的子进程,运行一些所需的代码,然后等待任何/所有子进程完成运行:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define printPID printf("my pid = %d, parent pid = %d\n", getpid(), getppid());

void fork_error() {
  perror("Failed to fork.");
  exit(1);
}

void fork_child(void (*f)()) {
  int pid;
  if ((pid = fork()) == 0) {
    f();
    wait(NULL);
    exit(0);
  } else if (pid < 0) {
    fork_error();
  }
}

/* Function prototypes */
void A(), B(), C(), D(), E(), F();

void A() {
  fork_child(B);
  fork_child(C);
  /* Code for A goes here */
  printPID;
  wait(NULL);
}

void E() {
  /* Code for E goes here */
  printPID;
}

void F() {
  /* Code for F goes here */
  printPID;
}

void C() {
  fork_child(E);
  fork_child(F);
  /* Code for C goes here */
  printPID;
}

void D() {
  /* Code for D goes here */
  printPID;
}

void B() {
  fork_child(D);
  /* Code for B goes here */
  printPID;
}

int main(int argc, char *argv[]) {
  A();
  return 0;
}

示例输出:

$ ./a.out
my pid = 17365, parent pid = 14178
my pid = 17366, parent pid = 17365
my pid = 17369, parent pid = 17367
my pid = 17368, parent pid = 17366
my pid = 17367, parent pid = 17365
my pid = 17370, parent pid = 17367

如果您还需要每个节点/进程中的子 PID,则让 fork_child() 返回一个包含子 PID 的 int。

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2019-07-27
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多