Section outline

  • 在此任务中,我们研究子进程如何从其父进程获取环境变量。在 Unix 系统中,fork() 通过复制调用进程来创建新进程。新进程(称为子进程)是调用进程(称为父进程)的副本。然而,有些内容并不会被子进程继承(请通过命令 man fork 查看 fork() 的手册)。在此任务中,我们想了解父进程的环境变量是否会被子进程继承。

      • 请编译并运行以下程序,并描述你的观察结果。该程序可以在 Labsetup 文件夹中找到;可以使用 "gcc myprintenv.c" 编译,生成的二进制文件名为 a.out。运行它并使用 "a.out > file" 将输出保存到文件中。

        #include <unistd.h>
        #include <stdio.h>
        #include <stdlib.h>
        
        extern char **environ;
        void printenv()
        {
          int i = 0;
          while (environ[i] != NULL) {
             printf("%s\n", environ[i]);
             i++;
          }
        }
        
        void main()
        {
          pid_t childPid;
          switch(childPid = fork()) {
            case 0:  /* 子进程 */
              printenv();          ①
              exit(0);
            default:  /* 父进程 */
              //printenv();        ②
              exit(0);
          }
        }
      • 注释掉子进程情况中的 printenv() 语句(①),并取消注释父进程情况中的 printenv() 语句(②)。再次编译并运行代码,并描述您的观察结果。将输出保存到另一个文件中。