- 论坛徽章:
- 0
|
本帖最后由 crazyhadoop 于 2013-11-13 22:21 编辑
程序1:
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- int g_a = 1;
- int main(void){
- int l_b = 1;
- pid_t p;
- if((p = vfork()) < 0){
- perror("fork");
- }else if(p == 0){
- g_a++;
- l_b++;
- }
- printf("ppid = %d,pid = %d,g_a = %d,l_b = %d\n", getppid(), getpid(), g_a, l_b);
- return 0;
- }
复制代码 代码执行时出现段错误:
yan@yan-vm:~/apue$ ./a.out
ppid = 4101,pid = 4102,g_a = 2,l_b = 2
ppid = 3791,pid = 4101,g_a = 2,l_b = 1
Segmentation fault (core dumped)
如果在子进程中加入exit或者_exit函数后就能成功运行。
程序2:
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- int g_a = 1;
- int main(void){
- int l_b = 1;
- pid_t p;
- if((p = vfork()) < 0){
- perror("fork");
- }else if(p == 0){
- g_a++;
- l_b++;
- exit(0);
- }
- printf("ppid = %d,pid = %d,g_a = %d,l_b = %d\n", getppid(), getpid(), g_a, l_b);
- return 0;
- }
复制代码 yan@yan-vm:~/apue$ ./a.out
ppid = 3791,pid = 4115,g_a = 2,l_b = 2
在程序1中子进程最后执行了return 0,在程序2中子进程最后执行了exit(0),这两个语句的效果不应该是一样的么?如果不一样,区别是什么? |
|