ubuntu下调用fork,子进程只copy父进程的主线程

  由于本人才疏学浅,本文难免存在遗漏之处,欢迎大家留言指正,本人将感激不尽。
  
  最近在看《Operating system concepts》的4.6.1小节时候发现,fork将产生一个新的子进程,那么父进程的所有线程是否copy至子进程呢?
  为此,我写了如下代码来验证,此实验在ubuntu16.04-LTS下进行:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int i = 0;

void *pf(void *args){
    while(1){
        printf("%d\n", i);
        sleep(1);
    }
    return NULL;
}

int main(){
    pthread_t ppid;
    pthread_create(&ppid, NULL, &pf, NULL);

    pid_t pid;
    if((pid = fork()) == 0){
        i = 1;
    }

    while(1)
        ;

    return 0;
}

  首先,父进程创建了一个子线程,该子线程每秒输出一次变量 i 的值。接着,父进程创建一个子进程,在子进程内将变量 i 赋值为1。为了避免父进程立即退出,最后父进程将进入一个死循环。
  

  我们可以通过观察输出结果来判断父进程通过fork创建子进程时,是否copy所有的线程至子进程。若:
  1、输出结果为0,1相继出现,那么父进程在fork时,将copy父进程的所有线程。
  2、若输出结果只有0,则父进程在fork时,仅仅copy父进程中调用fork的线程至子进程。

  此处,输出结果为第二种情况,即在ubuntu16.04-LTS下,父进程fork子进程时,仅仅copy调用fork的线程至子进程。

  其实,具体的结果可能与系统相关,《Operating System Concepts》书中指出,某些UNIX系统提供两个版本的fork,一个版本的fork会copy所有的线程至子进程,另外一个版本的fork只copy调用fork系统调用的线程至子进程。

  若同样在ubunutu16.04-LTS下执行如下代码,将产生什么输出呢?

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int i = 0;

void *pf(void *args){
    pid_t pid;
    if((pid = fork()) == 0){
        i = 1;
    }

    while(1){
        printf("%d\n", i);
        sleep(1);
    }
    return NULL;
}

int main(){
    pthread_t ppid;
    pthread_create(&ppid, NULL, &pf, NULL);

    while(1)
        ;

    return 0;
}

  显然,按照上面的分析,输出结果为:每秒输出一个0和1。

猜你喜欢

转载自blog.csdn.net/nice_wen/article/details/80618486