繁体   English   中英

Unix C 编程:多个管道和分支

[英]Unix C Programming: multiple pipes and forks

我正在尝试根据可用 CPU 的数量解决分配问题。 然后我需要相应地创建子进程的数量和两个管道来在父进程与每个子进程之间进行通信。 例如有 4 个可用的 CPU,我需要创建 3 个孩子(fork() 3 次),并创建 6 个管道。 我搜索了不同的来源,他们通常创建 eg// int pipefd[2] 然后 pipe(pipefd); 我的第一个想法是在找出 CPU 数量后,我按照以下代码构建矩阵:

  /* Find # of CPU and minus 1 */
  cpu_num = (sysconf (_SC_NPROCESSORS_ONLN)) - 1;

  /* Pipe creation */
  /* 2 Pipes for 1 child */
  enum {p_read, p_write};
  for (i = 0; i < (cpu_num); i++) {
    int ptcfd[i][2];
    if (pipe(ptcfd[i]) < 0) {
      perror("Parent to Child Pipe Error");
      exit(20);
    }
    int ptpfd[i][2];
    if (pipe(ptpfd[i]) < 0) {
      perror("Child to Parent Pipe Error");
       exit(20);
    }
  }

  char buf[PIPE_BUFF_LEN]; /* create Buffer with size 1024 */

  /* Array to store children PID */
  int childid[cpu_num];

  /* Children preparation task */
  for (i = 0; i < cpu_num; i++) {
    pid = fork();
    /* Failed to fork section */
    /* Creating error message */
    if (pid < 0) {
      printf("Failed to create fork PID #%d. \n\n", getpid());
      exit(44);
    }

    /* Parent */
    /* Record PID into childid array for later use */
    if (pid > 0) {
        close(ptpfd[i][p_write]);
        close(ptcfd[i][p_read]);
        childid[i] = pid;
    }
    /* Child */
    if (pid == 0) {
        close(ptcfd[i][p_write]);
        close(ptpfd[i][p_read]);
    }
  }

假设我有 4 个 CPU。 但是当我尝试编译时,这些似乎不对,它说: main.c:138:12: error: 'ptpfd' undeclared (first use in this function) close(ptpfd[i][p_write]);

main.c:138:12:注意:每个未声明的标识符只针对它出现的每个函数报告一次

main.c:139:12: 错误: 'ptcfd' 未声明(第一次在这个函数中使用) close(ptcfd[i][p_read]);

所以我开始想(但无法通过谷歌搜索确认)也许我不需要使用矩阵来创建 6 个管道,我只需要创建常规的 2 路管道:ptpfd[2] 和 ptcfd[2],然后在我 fork() 之后,每个孩子只会继承自己的 2 个管道? 如果我的假设是错误的,请帮助我,谢谢

C 实现了变量的块作用域。 您在调用pipe()的第一个for循环中声明ptpfdptcfd数组,然后尝试在调用fork()的第二个for循环中使用它们。 您应该在循环之外声明数组,以便它们在整个函数中可见。

此外,数组的大小是错误的。 您声明了int ptpfd[i][2] 因此,在循环的第一次迭代中,它将是一个 0x2 数组,在第二次迭代中它将是一个 1x2 数组,在第三次迭代中它将是 2x2,依此类推。 数组的大小应基于您要分叉的进程数,即cpu_num ,因此应声明:

int ptpfd[cpu_num][2];
int ptcfd[cpu_num][2];

然后, i将成为每个子进程管道的这些数组的索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM