5叉后只有1个孩子(C)

时间:2016-09-15 13:29:49

标签: c process fork pid

我正在尝试在C中创建处理器场。我首先打开消息队列,然后尝试创建工作进程:(注意NROF_WORKERS是5)

static void
makechildren (void) {
    // Only the parent should fork. Any children created will become workers. 
    pid_t   processID; 
    pid_t   farmerPID = getpid(); // To identify who the farmer is

    // Loop creating processes, indexed by NROF_WORKERS
    int i = 0; 
    while (i < NROF_WORKERS){
        if (getpid() == farmerPID){
            i++; 
            printf ("Parent is creating a child!%d\n", getpid()); 
            processID = fork();
        }
    }

    if (processID < 0){
        perror("fork() failed");
        exit(1);
    }
    else {
    // If parent, start farming
        if (processID == farmerPID) {
            printf("Parent reporting in!%d\n");
        }
    // If child, become a worker
        if (processID == 0) {
            printf("Child reporting in!%d\n", getpid()); 
            join();
        }
    }
}

正如您所看到的,我希望父母在任何时候创建一个孩子,然后我希望父母和所有孩子都要报告。但是,这就是我得到的:

Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Child reporting in!11914

现在,我注意到11909和11914的区别是5.所以我的问题是:是否创建了其他进程?如果是这样,他们怎么不报告?如果没有,我做错了什么?此外,父母根本没有报道,这是怎么造成的?

2 个答案:

答案 0 :(得分:2)

所有子节点都已创建,但会在while循环中永久循环,因为i仅针对父节点递增:

int i = 0; 
while (i < NROF_WORKERS){
    if (getpid() == farmerPID){    
        i++;             // <---- This is happening for the parent process only.
        printf ("Parent is creating a child!%d\n", getpid()); 
        processID = fork();
    }
}

唯一要终止的孩子是最后一个,i等于NROF_WORKERS

父母也是&#34;没有报告&#34;因为你检查的processID等于父PID永远不等于它,因为它等于最新的fork结果,即最新创建的子PID:

.........
 processID = fork();
.........
.........
 if (processID == farmerPID) {
            printf("Parent reporting in!%d\n");
 }

答案 1 :(得分:0)

您始终打印farmerPid!但是,当消息被打印5次时,您有效地创建了5个过程:

while (i < NROF_WORKERS){
    if (getpid() == farmerPID){
        i++; 
        printf ("Parent is creating a child!%d\n", getpid()); 
        processID = fork();
    }
}

如果您想打印子pids,那么您的代码必须在父级和子级之间产生影响,如:

while (i < NROF_WORKERS){
    if (getpid() == farmerPID){
        i++; 
        printf ("Parent is creating a child!\n"); 
        processID = fork();
        if (processID==0) { // child
            printf("I am the child %d\n",getpid());
        } else { // parent
            printf("Parent just created child %d\n",processID);
        }
    }
}