vfork()函数的使用
前言:
vfork()函数与fork()函数创建进程的区别:
区别一:
vfork()创建的子进程直接使用父进程的存储空间,不进行拷贝。、
区别而:
vfork()创建的子进程,是子进程先运行,当子进程调用exit(0)退出,父进程才执行。
代码如下:
1 #include <sys/types.h>
2 #include <unistd.h>
3 #include<stdio.h>
4 #include<stdlib.h>
5
6 int main()
7 {
8 pid_t pid;
9 int i=0;
10 pid=vfork();//调用vfork()函数
11 if(pid==0)
12 {
13 while(1)
14 {
15 //打印子进程进程号信息。
16 printf("The child process is running ! pid=%d \n",getpid());
17 sleep(2);
18 i++;
19 if(i==3)
20 {
21 //当子进程运行3 次就退出
22 printf("The child process will be exit !\n");
23 exit(0);
24 }
25 }
26 }else if(pid>0)
27 {
28 while(1)
29 {
30 //打印夫进程进程号信息。
31 printf("The parent process is running ! pid=%d \n",getpid());
32 sleep(2);
33 }
34 }
35 return 0;
36 }
运行结果:
@Embed_Learn:~$ ./a.out
The child process is running ! pid=4423
The child process is running ! pid=4423
The child process is running ! pid=4423
The child process will be exit !
The parent process is running ! pid=4422
The parent process is running ! pid=4422
The parent process is running ! pid=4422
The parent process is running ! pid=4422