ritratt
ritratt

Reputation: 1858

Why is the shared memory value changing when accessed from two different processes?

I am creating a shared memory between a parent and child. Then I write a value to the shared memory from the child & read it from the parent. But the values are different. Here is the code:

#include <sys/shm.h>
#include <sys/stat.h>
#include <stdio.h>

int main()
{
    int seg_id, pid;
    int fib1 = 1, fib = 1, temp;
    int i, tempsize;
    int *result;

    seg_id = shmget(IPC_PRIVATE, 8, S_IRUSR | S_IWUSR);
    result = (int *) shmat(seg_id, NULL, 0);

    printf("Enter size\n> ");
    scanf("%d", &tempsize);

    pid = fork();
    if (pid == 0) 
    {
         for(i = 0; i < tempsize; i++)
         {
             temp = fib;
             fib = fib + fib1;
             fib1 = temp;
         }
         printf("fib value %d\n", fib);

         result = fib;
         printf("result in child is %p\n", result);
         printf("child done\n");
    }               
    else if(pid > 0)
    {
        wait(0);
        printf("%p\n", result);
    }
    return 1;
}

Here is the output:

Enter size
5
fib value 13
result in child is 0xd
child done
0xb778f000

As you can see, the value of result printed is different when printed from child and parent. Why is this happening?

Also I tried doing: result = &fib but doing this always prints the address of result in both the processes (again different.)

Upvotes: 3

Views: 1355

Answers (4)

Ganesh Kale
Ganesh Kale

Reputation: 51

Look at the result is the integer pointer and how you assigning value to result.

it should be *result = fib

Upvotes: 1

C.B.
C.B.

Reputation: 8336

In addition to the other answers, result = fib says set the address of your int pointer to the value of fib. If you are trying to store the value of fib in result, you want *result = fib. If you run your code, you will see the address is the same in both parent and child.

So, if you wanted to see the value of the calculation in parent and child, changing to

*result = fib;
printf("result in child is %d\n", *result);

printf("result in parent is %d\n", *result);

Yields output

Enter size
 5
fib value 13
result in child is 13
child done
result in parent is 13

Upvotes: 3

Macattack
Macattack

Reputation: 1990

You print it first as a signed int %d, then as a pointer %p. The int value is 13, when printed as a pointer in hex, 13 is d.

Upvotes: 0

user395760
user395760

Reputation:

The value is the same, decimal 13 equals hexadecimal 0xD. The output is different because the format code is different: The parent uses %d, rendering the number in decimal, while the child uses %p, rendering the value in hexadecimal.

Using %p is incorrect, it means pointer and will give wrong output if void * is not the same size as int. It works in this case, and you can reliable get hexadecimal output using the %x (or %X) code.

Upvotes: 6

Related Questions