JAN
JAN

Reputation: 21865

Unexpected behavior with shared memory & forking?

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

Upvotes: 2

Views: 194

Answers (2)

ugoren
ugoren

Reputation: 16441

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.

Upvotes: 6

Marek
Marek

Reputation: 639

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

Upvotes: -1

Related Questions