为什么这两个地址不一样? [英] Why are these two addresses not the same?

查看:71
本文介绍了为什么这两个地址不一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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("\nIPC SHARED MEMORY");
    printf("\n SENDER ADDRESS");
    printf("\nTHE ADDRESS IS %p",addr1);
    printf("\nENTER THE MESSAGE:");
    scanf("%s",addr1);
    printf("\nMESSAGE 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("\nIPC SHARED MEMORY");
    printf("\n SENDER ADDRESS");
    printf("\nTHE ADDRESSS IS %p",addr1);
    printf("\nMESSAGE STORED IN %p IS %s",addr1,addr1);

}

输出:

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?

推荐答案

共享内存可以映射到不同进程地址空间中的不同区域.这是完全正常的.但是如果你在共享内存中存储指向共享内存其他部分的指针,那么你就有麻烦了.您需要使用类似 偏移指针 在那种情况下.

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.

这篇关于为什么这两个地址不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆