分叉循环

时间:2014-03-11 19:04:52

标签: c loops fork

说我有一个过程。我叉了它,然后它有一个父母和一个孩子。 我希望父级从2到n写入管道,孩子从中读取。

孩子会在某些条件下通过每个值,并且他们没有通过任何条件,它会通过调用exit()返回父级。

在父语句中,我将需要分叉原始进程,现在当前父进程将读取3进入主进程中使用的fd并写入新创建的子进程,该子进程通过前一个子进程。< / p>

if (pid > 0){ //parent which writes n to fd
    close(fd[0]); //close read
    for (j = 2; j <= n; j++){
        if (write(fd[1], &j, sizeof(int)) == -1){ //write j = 2 to fd
            perror("write j");
        }
    }
    close(fd[1]); //close write

    int status;

    if(wait(&status) != -1){
        if (WIFEXITED(status)){
            if (WEXITSTATUS(status) == 2){
                pid = fork() //should I even be calling fork here?
        }
    }
}

else{ //CHILD        
    close(fd[1]); //close write
    for (j = 2; j <= n; j++){
        if (read(fd[0], &j, sizeof(int)) == -1){ //read j from fd
            perror("read j");
        }
    if (SOME CONDITION){
        exit(2);
    }

到目前为止,这只能让我通过值2,而且我不确定父母将值3发送到下一个孩子。

如果我的解释令人困惑,请参阅此图。

enter image description here

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

您必须在父进程中打开管道的子端,并将其传递给创建的下一个子级。对不起,暂时还没有使用linux,我现在还没有linux盒子,但我想,因为这是一种伪代码,尝试不会太痛苦。如果你想能够传递一个任意的n,你必须循环或使用递归,最好是循环,因为它不会为每次迭代使用堆栈内存。

也不完全确定我明白你要做什么,所以我做了一些猜测。所以,像:

int keep_going = 1;
while(keep_going){
     pid = fork(); 
     if (pid > 0){ //parent which writes n to fd

/* can't close read, have to pass it to next child
          close(fd[0]);*/  //close read
          for (j = 2; j <= n; j++){
               if (write(fd[1], &j, sizeof(int)) == -1){ //write j = 2 to fd
                    perror("write j");
               }
          }
/* can't close write either, since it gets closed in child, so that
          would have to be rewritten to check if it is open before
          closing.  close(fd[1]);*/ //close write

          int status;

          if(wait(&status) != -1){
               if (WIFEXITED(status)){
                    if (WEXITSTATUS(status) == 2){
                         continue;  /* continues the while loop */
                    } 
                    /* handle errors */
                    break;
               }
               /* handle errors */
               break;
          }
          /* handle more errors */
          break;
          assert(0); /* shouldn't be here */
     }

     else{ //CHILD
          close(fd[1]); //close write
          for(;;) {  /* child needs its own loop */
               for (j = 2; j <= n; j++){
                    if (read(fd[0], &j, sizeof(int)) == -1){ //read j from fd
                         perror("read j");
                    }
                    if (SOME CONDITION){
                         exit(2);
                    }
                    /* going to repeat for(;;) loop for next n */
               }
           }
     }
     assert(0); /* shouldn't be here */
}