How to share existing char * with an other process?

走远了吗. 提交于 2019-12-23 21:01:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18946281/how-to-share-existing-char-with-an-other-process

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