Printing same physical address in a c program

限于喜欢 提交于 2019-12-11 16:45:21

问题


Is there is a way to print the same physical address in these programs (while using the shared memory concept) rather than printing different logical addresses?

The reason for me to print the same physical address :...

/*It's optional to read this, since I have provided a lot of information which is not to the core */

In my lab, I have two programs: one to store a string in a physical memory via shared memory concept and one to print the same string via accessing the shared memory.

Program 1:

#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);
}

Program 2:

#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);
}

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 helloworld
tamil@ubuntu:~/myc$ cc shmget2.c
tamil@ubuntu:~/myc$ ./a.out

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

Here these programs are printing the 2 different logical address. But (to satisfy the college professor) is there is a way to print the same physical address? Please help..


回答1:


  • Your programs are most likely already doing exactly what your professor asked you to do.
  • You are totally not understanding the concept of physical vs. virtual addresses. On any operating system that uses virtual memory, a regular application (as opposed to the OS itself) can not know any physical addresses at all.


来源:https://stackoverflow.com/questions/5291104/printing-same-physical-address-in-a-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!