• Home
  • Jobs
  • coursesAndChallenges
  • Teachers
  • For business
  • Blog
  • ES/EN

0

13
Views
Variables after fork

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?

13 days ago ·

Santiago Trujillo

3 answers
Answer question

0

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.

13 days ago · Santiago Trujillo Report

0

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.

13 days ago · Santiago Trujillo Report

0

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".

13 days ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.