0

こんにちは皆さん、たとえば端末と同じようにパイプ (|) を実装することになっている次のコードがあります。ソート | メインをgrepします。これは、パイプを処理するコードの一部です。

    int pp[numPipes*2];
    for(i = 0; i < numPipes; i++){
        if(pipe(pp + i*2) < 0){ perror("pipe failed"); exit(-1); }
    }

    char **hold[numPipes+1];

    int j = 0;
    hold[j++] = args;

    for(i = 0; i < nargs; i++){
        if(!strcmp(args[i], "|")){
            hold[j++] = args+i+1;

            args[i] = NULL;

        }       
    }
    hold[j] = NULL;
    i = 0;
    j = 0;

    while(hold[i][0]){

      pid = fork();

      if(pid == 0) { //child process 

            if(i != 0){
            dup2(pp[(i-1)*2], 0);
        }

        if(i != numPipes){
            dup2(pp[i*2+1], 1);
        }
        int c;
        for( c = 0; c < 2 * numPipes; c++ ){
                close( pp[c] );
        }

        execvp(hold[i][0], hold[i]);
        //return only when exec fails 
        perror("exec failed");
        exit(-1);

      } else if(pid > 0) {//parent process 


        if(!async){

            //waitpid(-1, NULL, 0);

        }else printf("this is an async call\n");

      } else { //error occurred 
        perror("fork failed");
        exit(1);
      }
    i++;

    }

    int c;
    for( c = 0; c < 2 * numPipes; c++ ){
        close( pp[c] );
    }
    for(i = 0; i < numPipes+1; i++){
        wait(&status);
    }

このコードは機能し、コマンドを正しく実行しますが、実行するたびにセグメンテーション違反が発生し、発生しないはずの親プロセスが強制終了されます。このセグメンテーション違反が発生している場所を誰かが見ていますか? 私はそれを見つけることができません。

4

0 に答える 0