【问题标题】:Multiple Child Processes from one Parent Process来自一个父进程的多个子进程
【发布时间】:2016-07-27 02:28:24
【问题描述】:

我正在使用 fork 实现一个简单的父/子进程程序。我的目标是从单个父进程创建用户输入数量的子进程,并将它们的 PID 存储在动态数组中。我设法使用 fork 创建子进程(我认为)并存储它们的 PIDS。但是,当我存储 PID 时,我还存储了 0 PID 以及我认为与进程相关的另一个 PID,但这个数字比子进程和父进程大得多。

当这显然只在父进程内完成时,怎么会发生这种情况?

void createProcesses(int nProcess) {
  int i;
  int PID;
  processIDS = calloc(nProcess, sizeof(long));

  printf("*****Creating Processes*****\n");

  printf("Parent Process: PID %d\n", getpid());
  for (i = 0; i < nProcess; i++) {
    PID = fork();
    if (PID == 0) {
      printf("Child Process: PID %d\n", getpid());
      while(1){}
    }
    else if(PID != 0) {
      // sleep(3);
      // printf("Number of child processes created: %d\n", nProcess);
      // updateProcessList();
      *(processIDS + i) = PID;
      printf("%d\n", PID);
    }
  }
  for(i = 0; i < sizeof(processIDS); i++) {
    printf("%ld\n", *(processIDS + i));
  }
  while(1) {
    sleep(5);
    updateProcessList();
  }
}

processIDS is a long * global variable.

【问题讨论】:

    标签: c linux process fork


    【解决方案1】:

    问题出在这里:

      for(i = 0; i < sizeof(processIDS); i++) {
        printf("%ld\n", *(processIDS + i));
      }
    

    因为processIDS是一个指针,它的大小就是long *的大小,可能是4或8,这不是你想要的。如果nProcess 的值小于此值,您将读取动态分配数组的末尾,调用未定义的行为。

    您知道创建了nProcess 进程,因此将其用于循环测试:

      for(i = 0; i < nProcess; i++) {
        printf("%ld\n", *(processIDS + i));
      }
    

    【讨论】:

    • 也可以考虑使用processIDs[i],它比基于指针的变体更容易阅读。
    猜你喜欢
    • 2017-06-29
    • 2015-12-18
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2017-04-15
    • 1970-01-01
    相关资源
    最近更新 更多