1

これはクラス用なので、子プロセスが戻ったときに変数 nChars が設定されていない理由を理解しようとしています。waitpid() が子プロセスを取得することを読みましたが、nChars を印刷しようとすると、子の nChars がコマンドライン文字の数である場合でもゼロが表示されます

int main(int argc, char **argv)
{
    // set up pipe
  int      fd[2], status;
  pid_t    childpid;

  pipe(fd);
    // call fork()
  if((childpid = fork()) == -1){
    perror("pipe");
    return -1;
  }
  if (childpid == 0) {
        // -- running in child process --
        int     nChars = 0;
        char    ch;

        close(fd[1]);
        // Receive characters from parent process via pipe
        // one at a time, and count them.

        while(read(fd[0], &ch, 1) == 1)nChars++;

        // Return number of characters counted to parent process.
        printf("child returns %d\n", nChars);
        close(fd[0]);

        return nChars;
    }
    else {
        // -- running in parent process --
        int     nChars = 0;
        close(fd[0]);

        printf("CS201 - Assignment 3 - \n");

        // Send characters from command line arguments starting with
        // argv[1] one at a time through pipe to child process.

        for(int i=1; i < argc; i++)
            write(fd[1], argv[i], strlen(argv[i]));


        // Wait for child process to return. Reap child process.
        // Receive number of characters counted via the value
        // returned when the child process is reaped.

        waitpid(childpid, &status, WNOHANG);
        printf("child counted %d characters\n", nChars);
        close(fd[1]);
  return 0;
  }
4

1 に答える 1