1.vfork并不将父进程地址空间完全复制到子进程,在exec和exit之前在父进程的空间里运行。
2.vfork保证子进程先运行,在它调用exec或exit之后父进程才被调用。
验证的原代码:
#include "apue.h"
int grobval = 7;
int main()
{
int val = 90;
pid_t pid;
printf("before vfork\n");
if ((pid = vfork()) < 0){
err_sys("vfork error");
}
else if (pid == 0){
grobval++;
val++;
_exit(0);
}
//下面为父进程自己的。
printf("pid = %d, grobval = %d, val = %d\n",getpid(),grobval,val);
exit(0);
}
编译运行结果
gcc -Wall -ggdb3 -o vfork_value 8_3.c
In file included from apue.h:132,
from 8_3.c:1:
error.c: In function `err_doit':
error.c:121: warning: implicit declaration of function `vsnprintf'
error.c:123: warning: implicit declaration of function `snprintf'
8_3.c: In function `main':
8_3.c:12: warning: implicit declaration of function `vfork'
8_3.c:21: warning: int format, pid_t arg (arg 2)
./vfork_value
before vfork
pid = 20470, grobval = 8, val = 91
子进程修改了父进程里变量的值因为vfork子进程在父进程地址空间里。
注释掉子进程里的_exit后
1 #include "apue.h"2
3 int grobval = 7;
4
5 int main()
6 {
7 int val = 90;
8 pid_t pid;
9
10 printf("before vfork\n");
11
12 if ((pid = vfork()) < 0){
13 err_sys("vfork error");
14 }
15 else if (pid == 0){
16 grobval++;
17 val++;
18 // _exit(0);
19 }
20
21 printf("pid = %d, grobval = %d, val = %d\n",getpid(),grobval,val);
22 exit(0);
23
24 }
编译运行结果:
gcc -Wall -ggdb3 -o vfork_value_without 8_3.c
In file included from apue.h:132,
from 8_3.c:1:
error.c: In function `err_doit':
error.c:121: warning: implicit declaration of function `vsnprintf'
error.c:123: warning: implicit declaration of function `snprintf'
8_3.c: In function `main':
8_3.c:12: warning: implicit declaration of function `vfork'
8_3.c:21: warning: int format, pid_t arg (arg 2)
./vfork_value_without
before vfork
pid = 6994, grobval = 8, val = 91
pid = 6993, grobval = 8, val = 91
把_exit换为exit后呢?
./vfork_value_exit
before vfork
pid = 15599, grobval = 8, val = 91
结果应该是不定的。他依赖于io库的实现。可能是增加后的值也可能是没有输出。因为exit时已经缓冲了io。