2

Given the following code :

#include <sys/types.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/types.h>
int main()
{
    int arr[100];
    int shmid  = shmget(IPC_PRIVATE, sizeof(int), 0600);
    int *ptr = shmat(shmid, NULL, 0);
    *ptr = 42;
    arr[0] = 1;

    if (fork())
    {
        wait(NULL);
        printf("%d, %d\n",arr[0],*ptr);
    }

    else
    {
        arr[0] = 2;
        *ptr = 1337;
    }
    return 0;
}

The output is : 1,1337 .

Question : why it is not 2,1337 ?

How could that be if the child updates the arr and ptr is his block ? meaning , the father process updated arr[0] to be 1 before the fork() took place , then why the update of ptr took place and the update of arr[0] to value of 2 did not ?

Best regards

JAN
  • 21,236
  • 66
  • 181
  • 318
  • make sure to release the shared memory objects eventually as these will survive your program termination. See also http://stackoverflow.com/a/10685112/1025391 – moooeeeep Jul 23 '12 at 07:23

2 Answers2

6

arr is not shared between the parent and child.
After fork, each of them has a different copy of it. So when the child changes arr, it doesn't affect the parent.
Your shared memory calls affect ptr, but not arr.

ugoren
  • 16,023
  • 3
  • 35
  • 65
-1

Arrays are not pointers! Array may be stored on the stack. Check assembly code.

Marek
  • 439
  • 2
  • 5
  • 12