簡體   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