Process creation fork function

#include <sys/types.h>

#include <unistd.h>

    pid_t fork(void);

    Function: Used to create child processes.

    return value:

        The return value of fork() will be returned twice. Once in the parent process and once in the child process.

        In the parent process: Returns the ID of the created child process. Returns -1 to indicate creation failure, and sets errno.

        In the child process, returns 0.

        How to distinguish: return value through fork.

#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
int main() {
    //创建子进程
    pid_t pid = fork();
    //判断是父进程还是子进程
    if(pid > 0) {
        printf("pid: %d\n", pid);
        printf("I am parent process, pid : %d, ppid : %d\n", getpid(), getppid());
    } else if(pid == 0) {
        printf("I am child process, pid : %d, ppid : %d\n", getpid(), getppid());
    }
    for(int i = 0; i < 5; i++) {
        printf("i : %d\n", i);
    }
    return 0;
}

The  child process and the parent process run in separate memory spaces.  At the time of fork() both memory spaces have the same content.  Memory writes, file  mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect the other. 

#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
int main() {
    //创建子进程
    pid_t pid = fork();
    int num = 11;
    //判断是父进程还是子进程
    if(pid > 0) {
        printf("pid: %d\n", pid);
        printf("parent num : %d\n", num);
        num += 10;
        printf("parent num : %d\n", num);
        printf("I am parent process, pid : %d, ppid : %d\n", getpid(), getppid());
    } else if(pid == 0) {
        printf("child num : %d\n", num);
        num += 20;
        printf("child num : %d\n", num);
        printf("I am child process, pid : %d, ppid : %d\n", getpid(), getppid());
    }
    for(int i = 0; i < 5; i++) {
        printf("i : %d\n", i);
    }
    return 0;
}

Share when reading, copy when writing

 

Guess you like

Origin blog.csdn.net/ME_Liao_2022/article/details/132914617