【发布时间】:2020-08-06 06:05:15
【问题描述】:
我尝试使用 fork() 创建子进程,并尝试检查子进程的代码和数据段。但是这两个进程都指向同一个位置。
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
static int global_var = 10;
void increment(int *var){
printf("Incrementing @%p\n", var);
*var += 1;
}
void decrement(int *var){
printf("Decrementing @%p\n", var);
*var -= 1;
}
void do_operation(void (*my_ops)(int *)){
my_ops(&global_var);
printf("@Adr=0x%p, Global Val = %d\n", &global_var, global_var);
}
int main(){
int i, local_var;
pid_t pid;
pid = fork();
switch(pid){
case -1:
printf("Failed to create new Process.\n");
break;
case 0:
printf("Calling do_operation(), which is @%p\n", &do_operation);
for(i=0; i<5; i++){
printf("Child Process with pid(%d), ", getpid());
do_operation(&decrement);
sleep(1);
}
break;
default:
printf("Calling do_operation(), which is @%p\n", &do_operation);
for(i=0; i<5; i++){
printf("Parent Process with pid(%d), ", getpid());
do_operation(&increment);
sleep(1);
}
wait(NULL);
break;
}
return 0;
}
两个进程的代码段和数据段都指向同一个地址。可以看到如下输出。
Calling do_operation(), which is @0x55d37fd34846
Parent Process with pid(2718), Incrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 11
Calling do_operation(), which is @0x55d37fd34846
Child Process with pid(2719), Decrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 9
Parent Process with pid(2718), Incrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 12
Child Process with pid(2719), Decrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 8
Parent Process with pid(2718), Incrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 13
Child Process with pid(2719), Decrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 7
Parent Process with pid(2718), Incrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 14
Child Process with pid(2719), Decrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 6
Parent Process with pid(2718), Incrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 15
Child Process with pid(2719), Decrementing @0x55d37ff35010
@Adr=0x0x55d37ff35010, Global Val = 5
你可以看到两个进程中静态变量的地址是相同的。这是为什么呢?
【问题讨论】: