父进程不获取子 return 变量

Parent process does not reap child return variable

这是针对 class 的,所以我想了解为什么当子进程 returns 时未设置变量 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;
  }

父子不共享内存,所以他们有不同的变量nChars。子项是父项的副本,因此当您更改副本中的某些变量时,它们不会在原始变量中更改。 如果您需要从两个执行流程中看到一个变量,请使用线程。

您正在从子进程返回 nChars 作为进程退出代码,因此它将位于状态变量中。 尝试:

waitpid(childpid, &status, 0);
// removed WNOHANG because with it parent won't wait for child to exit
printf("child counted %d characters\n", status);

但是最好使用管道或套接字等IPC机制在子进程和父进程之间传输数据,因为退出代码是程序退出状态,退出代码0表示一切正常,其他退出代码表示一些事情出错了,退出代码不是用于传输任意数据