我正在尝试使用 shmget
和 shmat
与其他 forked+execed 进程共享一些内存:
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");
}
这很好用。
问题是 test[]
将是一个巨大的 char*
。所以我喜欢轻松分享 text[]
而不是复制它。有没有更好的方法来处理这个问题?
最佳答案
如果您可以读取文件大小或要从文件和位置读取的确切内存,则可以使用 mmap 将文件的那部分映射到内存。
关于c - 如何与其他进程共享现有的 char *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18946281/