C++ fork函数理解

C++的fork函数用来“复制”一份主程序,即创建主进程的子进程。调用fork的同时,我的理解是,已经在内存中创建了“副本”进程,同时返回pid,所以在返回值之前,已经是主进程和子进程同时在运行了(如果fork成功的话),这样,在程序的运行过程中,一次fork返回了两次值,在父进程中,fork返回新创建子进程的进程ID,在子进程中,fork返回0,这时候就能够同时跑两个进程了。
实列如下:

#include <stdio.h>
#include <unistd.h>

int main(int argc,char *argv[]){
    //fork函数使用
    int i = 0;
    printf("before fork\n");
    pid_t pid = fork();
    printf("after fork\n");
    if (pid < 0){
        printf("error\n");
        return 1;
    }
    else if (pid == 0){
        printf("fork success,this is son process\n");
        while (i<10){
            i += 1;
            printf("this is son process,i=%d\n",i);
            sleep(1);
        }
    }
    else{
        printf("fork success,this is father process,son process id is %d \n",pid);
        while (i<10){
            i += 2;
            printf("this is father process,i=%d\n",i);
            sleep(2);
        }
    }
    return 0;
}

运行结果:

before fork
after fork
fork success,this is father process,son process id is 11054 
this is father process,i=2
after fork
fork success,this is son process
this is son process,i=1
this is son process,i=2
this is father process,i=4
this is son process,i=3
this is son process,i=4
this is father process,i=6
this is son process,i=5
this is son process,i=6
this is father process,i=8
this is son process,i=7
this is son process,i=8
this is father process,i=10
this is son process,i=9
this is son process,i=10

在程序中,我们可以看到,fork函数调用之后,输出了两个“after fork”,也就是程序已经存在两个进程在跑;有一个变量i,在fork之前定义,然后在fork之后的运行过程中,子进程和主进程中的i值互不影响,两个进程同时在执行,可以验证fork是将主进程的资源全部拷贝了一份给子进程,两个进程的资源是独立的,互不影响。

猜你喜欢

转载自blog.csdn.net/yidu_fanchen/article/details/80494041