问题
Here is a code:
int i=0;
pid_t pid;
puts("Hello, World!");
puts("");
pid = fork();
if(pid)
i=42;
printf("%p\n", &i);
printf("%d\n", i);
puts("");
And output
Hello, World!
0x7fffc2490278
42
0x7fffc2490278
0
Program print Hello, World! one time, so child process wasn't start from the beginning and it wasn't re-define variables. Adresses of variables are same. So they are same. But I change i's value in parent process which is executed first, it didn't change for child process. Why?
回答1:
Adresses of variables are same. So they are same. But I change i's value in parent process which is executed first, it didn't change for child process. Why?
The addresses are in the scope of a process. They are virtual addresses. Address 0x7fffc2490278
in the parent process and 0x7fffc2490278
in the child process are different physical addresses.
回答2:
When you do fork()
, a whole process will be created including variables. So i
in the parent is not i
of the child. They have same virtual address but not same physical address. The modification is completely independent.
回答3:
From the man page for fork:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
That is, for the parent pid is being set to a number greater than 0 (or -1 if failure which you should also check for).
if(pid)
evaluates to if(true)
And it will execute for the parent. The child, however, gets 0 assigned to pid
(that's how it knows it's the child).
if(0)
evaluates to if(false)
and thus the value of i does not change.
However, because of abstractions the process sees memory in virtual addresses (virtual address space which is exactly copied with fork
). Only the kernel can manage physical addresses and the process communicates with kernel to get this memory (the process just says "put this variable i
at this address: 0x7fffc2490278
" and the kernel will basically map it wherever it wants to). As far as the process knows, it's the only process asking for memory and that's why their addresses are the "same".
回答4:
Variables live in the virtual address space of the process. Address space of a process is local to that process. The fact that you see the same address in two processed does not mean that you are accessing the same variable. Not at all.
Address values make sense only within the context of its own process. It makes no sense to compare the addresses from different processes' address spaces.
Variable i
in parent process is completely separate from variable i
in child process. You changed only one i
(the parent's one), which is exactly what you observe in the output.
来源:https://stackoverflow.com/questions/31572782/variables-after-fork