linux 进程相关函数--fork vfork clone

2021-10-31, updated 2021-10-31

linux使用了写时复制技术,vfork速度优势变的并不明显,可以不使用这个了。

vfork不要使用return退出,只有使用exit()退出父进程才能正常运行

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    int count = 1;
    printf("father pid:%d\n count:%d\n", getpid(), count);
    int pid = vfork();

    if(pid < 0)
    {
        printf("fork error\n");
    }
    else if(pid == 0)
    {
        printf("this is son, count:%x pid:%d\n", ++count, getpid());
        sleep(2);
        printf("son end\n");
        exit(0);
    }
    else
    {
        printf("this is father, count:%x oud:%d\n", ++count, getpid());
        sleep(2);
        printf("father end\n");
        exit(0);
    }

    return 0;
}

运行结果

father pid:830
 count:1
this is son, count:2 pid:831
son end
this is father, count:3 oud:830
father end
words: 291 tags: linux-c