Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

shmget.c:

#include<sys/types.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
main()
{
    key_t key;
    int shmid;
    char* addr1;
    key = ftok("/home/tamil/myc/pws.c",'T');
    shmid = shmget(key,128*1024,IPC_CREAT|SHM_R|SHM_W);

    addr1 = shmat(shmid,0,0);

    printf("
IPC SHARED MEMORY");
    printf("
 SENDER ADDRESS");
    printf("
THE ADDRESS IS %p",addr1);
    printf("
ENTER THE MESSAGE:");
    scanf("%s",addr1);
    printf("
MESSAGE STORED IN %p IS %s",addr1,addr1);  
}

shmget2.c:

#include<sys/types.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>

main()
{
    int shmid;
    char* addr1;
    key_t key;


    key = ftok("/home/tamil/myc/pws.c",'T');
    shmid = shmget(key,128*1024,SHM_R|SHM_W);

    addr1 = shmat(shmid,0,0);


    printf("
IPC SHARED MEMORY");
    printf("
 SENDER ADDRESS");
    printf("
THE ADDRESSS IS %p",addr1);
    printf("
MESSAGE STORED IN %p IS %s",addr1,addr1);

}

Output:

tamil@ubuntu:~/myc$ cc shmget.c
tamil@ubuntu:~/myc$ ./a.out

IPC SHARED MEMORY
 SENDER ADDRESS
**THE ADDRESS IS **0xb786c000****
ENTER THE MESSAGE:helloworld

MESSAGE STORED IN **0xb786c000** IS helloworldtamil@ubuntu:~/myc$ cc shmget2.c
tamil@ubuntu:~/myc$ ./a.out

IPC SHARED MEMORY
 SENDER ADDRESS
**THE ADDRESSS IS **0xb7706000****
MESSAGE STORED IN **0xb7706000** IS helloworldtamil@ubuntu:~/myc$ 

This all works well. But the address is not the same. Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
190 views
Welcome To Ask or Share your Answers For Others

1 Answer

Shared memory can be mapped to different regions in the address space of different processes. This is perfectly normal. But if you're storing pointers inside the shared memory to other parts of the shared memory, then you're in trouble. You'll need to use something like an offset pointer in that case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...