问题描述
- vfork函数与父进程共享空间问题
-
//测试程序
#include "apue.h"int glob = 1;
int main(void)
{
int var = 1;
int pid;printf("before forkn"); if((pid = vfork()) < 0) { perror("fork error"); exit(-1); } else if(pid == 0) { glob++; var++; printf("pid = %d, glob = %d, var = %dn", getpid(), glob, var); //printf("glob_address: %pn", &glob); //printf("var_address: %pn", &var); _exit(0); } printf("pid = %d, glob = %d, var = %dn", getpid(), glob, var); //printf("glob_address: %pn", &glob); //printf("var_address: %pn", &var); return 0;
}
1 此时没有让程序输入var和glob变量的地址,运行结果为
before fork
pid = 15865, glob = 2, var = 2
pid = 15864, glob = 2, var = 1
2 取消掉注释后,运行结果为
before fork
pid = 25515, glob = 2, var = 2
glob_address: 0x804a050
var_address: 0xbfa4d4cc
pid = 25514, glob = 2, var = 2
glob_address: 0x804a050
var_address: 0xbfa4d4cc问题:(程序在codeblocks10.05中运行的,ubuntu12.04系统)
vfork创建一个进程后,在子进程调用exec或exit之前,它在父进程中执行,运行结果2也说明了这一点,var和glob的都被子进程给加1了,但是运行结果1的父进程var变并没有加1,貌似子进程没有共享父进程的堆栈空间一样,这是为什么?求帮助解答........
时间: 2025-01-20 12:43:56