0
votes

I'm trying to write a small program that forks processes from a single parent. Currently my code does this a few times but then the children create more child processes, which I want to eliminate.

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c > 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(i), getpid(i)); 
        }
    }
}

I'm not sure how to modify it so that fork is only forking from the parent though.

EDIT: thanks for the help, got the solution:

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c > 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(i), getpid(i)); 
        }

        else {
            exit(0); 
        } 
    } 
}
2
1) what is the variable 'n' supposed to be? it is not defined. Suggest using the value in the 'pid_t' variable. 2) The question is about a runtime problem, but the posted code does not compile. Please post the real code. - user3629249

2 Answers

0
votes

nothing in the posted code is recognizing the child (0 == pid)

so a child hits (and skips) the two 'if' statements.

hits the end of the loop,

branches back to the top of the loop, calls fork()....etc.

Suggest: adding

elseif( 0 == pid ) 
{ // then child ...   
    exit( EXIT_SUCCESS );
}
0
votes

The child process does not enter any part of the if block, and just loops back to the top of the for loop creating more children. Also, the if (n > 0) block gets run for the parent, not the child, since fork returns 0 to the parent and the child's pid to the parent.

Change if (n > 0) to if (n == 0), and call exit() at the bottom of the block to prevent the child from continuing. Also, getpid() and getppid() don't take any arguments.

int main() {
    pid_t c;

    for (int i = 0; i < 5; i++) { 
        c = fork(); 

        if(c < 0) { 
            perror("fork");
            exit(1);
        }
        else if( c == 0 ) { 
            printf("parentID = %d, childID = %d\n", getppid(), getpid()); 
            exit(0);    // <-- here
        }
    } 
}