【问题标题】:C Programing : Parent & Child ProcessC 编程:父子进程
【发布时间】:2013-09-19 22:24:09
【问题描述】:

鉴于以下代码,我正在尝试解决这个问题:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

char mynum='0';
int main(void)
{
   int i;
   pid_t fork_return;
   static char buffer[10];
   fork_return = fork();
   if (fork_return == 0)
   {
      strcpy(buffer, "CHILD"); /*in the child process*/
      for (i=0; i<5; ++i) /*both processes do this*/
      {
         mynum=i + '0';
         sleep(1); /*5 times each*/
         write(1, buffer, sizeof(buffer));
         write(1, &mynum, 1);
         write(1, "\n", 1);
      }
      return 0;
   }
   else
   {
      strcpy(buffer, "PARENT"); /*in the parent process*/
      for (i=0; i<5; ++i) /*both processes do this*/
      {
         sleep(1); /*5 times each*/
         write(1, buffer, sizeof(buffer));
         write(1, &mynum, 1);
         write(1, "\n", 1);
      }
      return 0;
   }
} 

注意mynum 是一个全局变量。

  • 孩子正在递增mynum 的 ASCII 值
  • 父母不是
  • 孩子和家长可以轮流跑步

为什么子打印CHILD0CHILD1CHILD2等,而父打印PARENT0PARENT0PARENT0等?记住mynum 是一个全局变量。

另外,如果我fork一个进程,为什么我打印他们的pid,他们的ppid总是一样的?

【问题讨论】:

    标签: c process parent pid


    【解决方案1】:

    父进程和子进程有单独的virtual address spaces。因此,子进程中全局变量的更新不会影响父进程中的全局变量。这是一项称为memory protection 的功能,其中分配给一个进程的内存通常不能被其他进程访问。

    pid,用getpid()检索,是进程的进程id,每个进程都有一个唯一的。使用getppid() 检索的ppid 是父进程ID。只要父进程还活着,父进程 id 就会是子进程 fork()d 所在的父进程的 pid。当子进程的父进程死亡时,子进程将被进程 ID 为 1 的init 进程继承。

    【讨论】:

      【解决方案2】:

      因为它是否是全局变量并不重要,所以您可以在单独的进程中使用它们。

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 1970-01-01
        • 2017-08-09
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-01
        • 1970-01-01
        相关资源
        最近更新 更多