【问题标题】:How many processes will be created将创建多少个进程
【发布时间】:2020-10-19 09:02:14
【问题描述】:

我有这段代码,想知道将创建多少个进程。我不确定,因为我认为循环将是 12 个进程,但也可能是 8 个。

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

int main() {
  pid_t childpid;
  int i;

  childpid = fork();

  for (i = 0; i < 3 && childpid == 0; i++) {

    if (childpid == -1) {
      perror("Failed to fork.");
      return 1;
    }

    fprintf(stderr, "A\n");

    childpid = fork();

    if (childpid == 0) {
      fprintf(stderr, "B\n");
      childpid = fork();
      fprintf(stderr, "C\n");
    }

  }

  return 0;
}

【问题讨论】:

  • 为什么你认为它可以是8?

标签: c linux unix fork posix


【解决方案1】:

是的,您可以使用 aptitude 来评估创建了多少进程,但我让程序为我决定。

子进程和父进程使用semaphore 同步,pcount 变量用于跟踪已创建进程的数量。每当childpid 被评估为零时,pcount 就会递增。以下是对您的计划的补充。

#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

int main(void)
{
    /* Initialize and setup a semaphore */

    sem_t* sema = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);

    if (sema == MAP_FAILED)
        exit(1);

    if (sem_init(sema, 1, 1) != 0)
        exit(1);

    /* Initialize pcount */

    int* pcount = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);

    if (pcount == MAP_FAILED)
        exit(1);

    *pcount = 1;

    printf("pcount = %d\n", *pcount);

    pid_t childpid;
    int i;

    childpid = fork();

    if (childpid == 0) {
        sem_wait(sema);
        *pcount = *pcount + 1;
        printf("pcount = %d\n", *pcount);
        sem_post(sema);
    }

    for (i = 0; i < 3 && childpid == 0; i++) {

        if (childpid == -1) {
            perror("Failed to fork.");
            return 1;
        }

        fprintf(stderr, "A\n");

        childpid = fork();

        if (childpid == 0) {

            sem_wait(sema);
            *pcount = *pcount + 1;
            printf("pcount = %d\n", *pcount);
            sem_post(sema);

            fprintf(stderr, "B\n");
            childpid = fork();

            if (childpid == 0) {
                sem_wait(sema);
                *pcount = *pcount + 1;
                printf("pcount = %d\n", *pcount);
                sem_post(sema);
            }

            fprintf(stderr, "C\n");
        }
    }

    return 0;
}

终端会话:

$ gcc SO.c -lpthread 
$ ./a.out
pcount = 1
pcount = 2
A
pcount = 3
B
C
pcount = 4
C
A
pcount = 5
B
C
pcount = 6
C
A
pcount = 7
B
C
pcount = 8
C

所以是的,8 就是答案。简单易懂:)

【讨论】:

    【解决方案2】:
    8 processes will be created. 
    

    这是第一个循环后的样子:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 2013-02-24
      • 2017-06-18
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      相关资源
      最近更新 更多