The use and principle of the fork function in C++

The use and principle of the fork function in C++. In C++, the fork function is used to create a new process called a subprocess, which is almost identical to the original process.

Basic overview of the fork function

After the fork() function is called successfully, there will be two return values. The current process, that is, the parent process returns the pid of the child process, and the child process returns 0. Returns -1 if the function call fails.

#include <stdio.h>
#include <unistd.h>
int main(void) {
    int i = 0;
    printf("i\tson/pa\tppid\tpid\tfpid\n");
    for (i = 0; i < 2; i++) {
        pid_t fpid = fork();
        if (fpid == 0)
            printf("%d\tchild\t%4d\t%4d\t%4d\n", i, getppid(), getpid(), fpid);
        else
            printf("%d\tparent\t%4d\t%4d\t%4d\n", i, getppid(), getpid(), fpid);
    }
    return 0;
}

operation result:

    i son/pa ppid pid fpid

    i son/pa ppid pid fpid
    0 parent 54861 57344 57345
    0 child 57344 57345 0
    1 parent 54861 57344 57346
    1 parent 57344 57345 57347
    1 child 57344 57346 0
    1 child 57345 57347 0

Here is a simple analysis:

1. After fork() of the process with pid 57344, 57345 is returned, which is the pid of a child process.

2. The return value of the child process is 0, obviously its parent process pid is 57344.

3. The for loop continues to execute;

4. At this time, the process with pid 56344 creates a child process with pid 56346.

5. The previous child process with the pid of 56345 acts as the parent process at this time, and it creates a child process with the pid of 56347.

6. Then, the processes of 56346 and 56347 continue to execute, and the program ends.

What the fork function does

#include<unistd.h>
pid_t fork(void)

Return value: pid_tIt is a process descriptor, which is essentially one int. If the fork function call fails, it returns a negative number, and if the call succeeds, it returns two values: 0 and the child process ID.

Function function: Create a new child process with the current process as the parent process, and copy all resources of the parent process to the child process, so that the child process exists as a copy of the parent process. The parent and child processes are almost identical, but there are also differences such as the parent and child process IDs are different.

After the fork function

If the program simply creates a new process that is almost exactly the same, then such a process is useless. Therefore, if we can replace the new child process with another program, we have successfully used a process to create a completely different child process. Regarding process replacement, I won’t go into details here, and I will mention it again later.

Guess you like

Origin juejin.im/post/7250710949140971577