- fork fork创造的子进程是父进程的完整副本,复制了父亲进程的资源,包括内存的内容task_struct内容
- vfork vfork创建的子进程与父进程共享数据段,而且由vfork()创建的子进程将先于父进程运行
- clone产生线程,可以对父子进程之间的共享、复制进行精确控制。
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
|