3

I'm trying to share some memory with an other forked+execed process using shmget and shmat:

char test[]="test";
int shID;
char *shptr;
key_t shkey = 2404;

shID = shmget(shkey, sizeof(char)*(strlen(test)+1), IPC_CREAT | 0666);
if (shID >= 0) {
    shptr = shmat(shID, 0, 0);
    if (shptr==(char *)-1) {
        perror("shmat");
    } else {
        memcpy(shptr, &test, strlen(test)+1);
        ....
        //forking and execing
        ....
        shmdt(shptr);
    }
} else {
    perror("shmget");
}

This works fine.

The thing is that test[] is going to be a huge char*. So I liked easy to share text[] instead of copying it.Is there any better way to handle this?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
corema
  • 33
  • 3
  • What is test[] storing? Can you not get the content of test[] once you have obtained shptr? Then you could completely get rid of test[]. – Étienne Sep 22 '13 at 17:07
  • I was thinking about that too. test[] gets its content from some parts of a file. I can't know how tall test[] will be, until I test is loaded. – corema Sep 22 '13 at 17:22
  • Can you read the size of the file and allocate enough memory to hold the whole file? It is not space-optimal since you seem to want to read just part of this file but it would do what you want. – Étienne Sep 22 '13 at 21:14
  • Yes I can do that. At the moment I'm working on a work around: I write the needed size directly in the file. – corema Sep 23 '13 at 05:08

1 Answers1

0

if you can read file size or exact memory which you want to read from file and location than you can use mmap to map that part of file to memory.

Rocker
  • 25
  • 5