2 muguan11 muguan11 于 2014.05.30 13:22 提问

关于vfork和fork运行过程

1 #include
2 #include
3 #include
4
5
6
7 int glob = 6;
8 char buf[] = "a write to stdout\n";
9
10 void err_sys(char str)
11 {
12 if (*str)
13 printf("%s\n", str);
14 }
15
16 int my_vfork(void)
17 {
18 int var = 66;
19 pid_t pid;
20
21 printf("before vfork\n");
22 if ((pid = vfork()) < 0)
23 err_sys("vfork error");
24 else if (pid == 0) {
25 glob++; var++;
26 _exit(0);
27 }
28 /*parent
/
29 printf("pid = %d, glob = %d, var = %d\n", pid, glob, var);
30 exit(0);
31 }
32
33 void my_fork(void)
34 {
35 int var = 88;
36 pid_t pid;
37
38 if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
39 err_sys("write error");
40 printf("before fork\n");
41
42 if ((pid = fork()) < 0)
43 err_sys("fork error\n");
44 else if (pid == 0) {
45 glob++;
46 var++;
47 }
48 else
49 sleep(2);
50
51 printf("pid = %d, glob = %d, var = %d\n", pid, glob, var);
52 }
53
54 int main(int argc, char *argv[])
55 {
56 my_fork();
57 sleep(5);
58 printf("sleep 10 sec!\n");
59 my_vfork();
60
61 return 0;
62 }
63
为什么上面这段代码的运行结果是:
a write to stdout
before fork
pid = 0, glob = 7, var = 89
pid = 9706, glob = 6, var = 88
sleep 10 sec!
before vfork
pid = 9708, glob = 8, var = 67
sleep 10 sec!
before vfork
pid = 9709, glob = 7, var = 67
当main函数为:
54 int main(int argc, char *argv[])
55 {
56 // my_fork();
57 // sleep(5);
58 printf("sleep 10 sec!\n");
59 my_vfork();
60
61 return 0;
62 }
运行结果为:
sleep 10 sec!
before vfork
pid = 9746, glob = 7, var = 67
为什么当没有fork的时候vfork只运行一次,但前面有fork的时候vfork会多运行一次?

Csdn user default icon
上传中...
上传图片
插入图片