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

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

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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;
}

运行结果

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