繁体   English   中英

将创建多少个进程

[英]How many processes will be created

我有这段代码,想知道将创建多少个进程。 我不确定,因为我认为循环将是 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;
}

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

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

#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;
}

端子 Session:

$ 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是答案。 十分简单:)

8 processes will be created. 

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM