3

If a process and its fork have different copies of the data, then why is their pointer the same?

In the example below, if count was shared between the parent and child processes, we would see count: 2. However, count is not shared. But then, why does &count return the same value in both the parent and child process?

Output:

count: 1 0x7fff5a617510
count: 1 0x7fff5a617510

Program:

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid;
    int count = 0;

    pid = fork();

    count++;
    printf("count: %d %p \n", count, &count);

    return 0;
}
Luqmaan
  • 2,052
  • 27
  • 34

1 Answers1

3

As noted in comments, this is because of virtual addressing. AFAIK there is no way to see the physical address, as this is handled by the kernel and the MMU.

Also, note than even if count was shared between the two process (using shared memory; see man shmget for example), there would be a race condition.

Xaqq
  • 4,308
  • 2
  • 25
  • 38