2015-11-10 87 views
0

在我的代码如下,我正在运行一个父进程,它分叉成两个子进程。在之后(getpid());,两个孩子都退出状态。Wait()运行两次?

然而,当我运行父进程,它在某种程度上总是决定运行两次父节(设置了两个不同的PID值),我只是不能让它只运行一次。有一种方法可以在获得一个值后等待停止吗?

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <string.h> 
#include <stdlib.h> 

void child(int n) { //n: child pid 
    printf("\nPID of child: %i \n", n); 

    //random number rand 
    int randFile = open("/dev/random", O_RDONLY); 
    int r; 

    if(rand < 0) 
    printf("ERROR: %s\n", strerror(errno)); 
    else { 
    unsigned int seed; 
    read(randFile, &seed, 4); //&rand is a pointer, 4 bytes 
    int randClose = close(randFile); 

    srand(seed); //seeds rand() with random from /dev/random 
    r = rand(); 

    if(randClose < 0) 
     printf("ERROR: %s\n", strerror(errno)); 

    //range between 5 and 20 seconds 
    r = r % 20; 
    if(r < 5) 
     r = 5; 
    } 
    // printf("\n%i\n", r); 
    sleep(r); 
    // sleep(1); 
    printf("\n child with pid %i FINISHED\n", n); 

    exit(r); 
} 

int main() { 
    printf("\nPREFORK\n"); 

    int parentPID = getpid(); 

    int child0 = fork(); 
    if(child0 < 0) 
    printf("ERROR: %s\n", strerror(errno)); 

    int child1 = fork(); 
    if(child1 < 0) 
    printf("\nERROR: %s\n", strerror(errno)); 

    if(getpid() == parentPID) 
    printf("\nPOSTFORK\n"); 

    //if children 
    if(child1 == 0) //using child1 as child-testing value b/c when child1 is set, both children are already forked 
    child(getpid()); 

    int status; 
    int pid = wait(&status); 

    //parent 
    if(getpid() != 0) { 
    if(pid < 0) 
     printf("\nERROR: %s\n", strerror(errno)); 
    if (pid > 0 && pid != parentPID) { 
     printf("\nPID of FINISHED CHILD: %i\n Asleep for %i seconds\n", pid, WEXITSTATUS(status)); 
     printf("PARENT ENDED. PROGRAM TERMINATING"); 
    } 
    } 
    return 0; 
} 
+6

请出示在此之前的代码为好,你要求的代码叉成两个子进程。如果我们看到代码在做什么,而不是猜测发生了什么,并且猜测child1设置为什么,那么更容易。还要注意,getpid()永远不会是0.您的进程始终有一个非零进程ID。 – nos

+0

完成。我没有意识到我们可以突出显示并点击方括号来批量添加代码。我其实只是在每一行上做了四个空格......谢谢。 – CodeSammich

回答

2

家长做:

int child0 = fork(); // + test if fork failed 
int child1 = fork(); // + test if fork failed 

首先你只有父。 1叉后你有父母和第一个孩子,无论在同一个执行点,所以才下叉了。 因此,在父母重新创建一个孩子之后,第一个孩子创建自己的孩子(并且将像父母一样行事)。

你必须让你相信,孩子不叉使用的if/else。即:

child0 = fork(); // add check for errors 
if (child0 == 0) { 
    // the 1st child just have to call that 
    child(getpid()); 
    exit(0); 
} 
// here we are the parent 
child1 = fork(); 
if (child1 == 0) { 
    // the 2nd child just have to call that 
    child(getpid()); 
    exit(0); 
} 

你可以这样做,当然,这只是一个例子。主要的一点是不要在小孩内拨打fork()

+0

噢,我的天啊。谢谢 – CodeSammich