How to use Fork() to create only 2 child processes?

倖福魔咒の 提交于 2019-11-28 19:33:23
pid = fork (); #1
pidb = fork (); #2

Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.

What you should do is something like this.

if(fork()) # parent
    if(fork()) #parent
    else # child2
else #child1
Fei Xue

After you create process , you should check the return value. if you don't , the seconde fork() will be executed by both the parent process and the child process, so you have four processes.

if you want to create 2 child processes , just :

if (pid = fork()) {
    if (pid = fork()) {
        ;
    } 
} 

You can create n child processes like this:

for (i = 0; i < n; ++i) {
    pid = fork();
    if (pid > 0) {   /* I am the parent, create more children */
        continue;
    } else if (pid == 0) { /* I am a child, get to work */
        break;
    } else {
        printf("fork error\n");
        exit(1);
    }
}

When a fork statement is executed by the parent, a child process is created as you'd expect. You could say that the child process also executes the fork statement but returns a 0, the parent, however, returns the pid. All code after the fork statement is executed by both, the parent and the child.

In your case what was happening was that the first fork statement created a child process. So presently there's one parent, P1, and one child, C1.

Now both P1 and C1 encounter the second fork statement. The parent creates another child (c2) as you'd expect, but even the child, c1 creates a child process (c3). So in effect you have P1, C1, C2 and C3, which is why you got 4 print statement outputs.

A good way to think about this is using trees, with each node representing a process, and the root node is the topmost parent.

you can check the value as if ( pid < 0 ) process creation unsuccessful this tells if the child process creation was unsuccessful.. fork returns the process id of the child process if getpid() is used from parent process..

You can create a child process within a child process. This way you can have 2 copies of the original parent process.

int main (void) {
    pid_t pid, pid2;
    int status;

    pid = fork();

    if (pid == 0) { //child process
        pid2 = fork();
        int status2;

        if (pid2 == 0) { //child of child process
            printf("friends!\n");
        }
        else {
            printf("my ");
            fflush(stdout);
            wait(&status2);
        }
    }
    else { //parent process
        printf("Hello ");
        fflush(stdout);
        wait(&status);
    }

    return 0;
}

This prints the following:

Hello my friends!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!