Where does code execution begin in a child process?

Consider the code:

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

/* main --- do the work */

int main(int argc, char **argv)
{
    pid_t child;

    if ((child = fork()) < 0) {
        fprintf(stderr, "%s: fork of child failed: %s\n",
            argv[0], strerror(errno));
        exit(1);
    } else if (child == 0) {
                    // do something in child
            }
    } else {
    // do something in parent
    }
}

My question is: where does the child process come from in the code, i.e. which line is executed first? If he executes all the code, he will also create his own child process, and everything will happen continuously, which is not happening for sure!

If it starts after the fork () command, how does this happen if the statement first?

+3
source share
4 answers

It starts the execution of the child in the fork function return. Not at the beginning of the code. The fork returns the pid of the child in the parent process and returns 0 in the child process.

+7
source

When executed, the fork()stream is duplicated in memory.

, , , , , , fork() .

fork() 0, if , .

fork(), , , , , , ( , )

+6

( ) fork. , fork .

+2

Well, if I understand your question correctly, I can tell you that your code will be launched as a process already. When you run the code, it is already a process, so this process will be executed anyway. After fork (), you will have another process (child process).

On Unix, a process can create another process, so this happens.

0
source

All Articles