天天看點

vfork函數

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

/* 
    vfork和fork的差別:
        .vfork建立的子程序和父程序共享線性位址空間;fork建立的子程序具有獨立的線性位址空間
        .vfork先執行子程序;fork子程序和父程序的執行順序是随機的
        .vfork建立的子程序中隻有在調用exit()或者execve()函數之後,父程序才可能被成功調用
*/

int main(void)
{
    pid_t fpid;

    int count = ;

    fpid = vfork();

    if (fpid == -) {
        perror("MSG");
    }

    else if (fpid > ) {
        printf("parrent: %d\n", getpid());
        count++;
        printf("count: %d\n", count)
    }

    else if (fpid == ) {
        printf("child: %d\n", getpid());
        count++;
        printf("count: %d\n", count);
        exit();
    }

    return ;
}

/*
    .執行結果:
    child: 
    count: 
    parrent: 
    count: 

    .如果子程序沒有調用exit(), 執行結果為:
    child: 
    count: 
    parrent: 
    count: 
    重複上面的列印結果
*/
           

繼續閱讀