マニュアルページを読んだ後、shm_openとは基本的にとshm_unlinkに類似していることを理解しましたが、違いは System V用で POSIX 用です。どちらもメモリ共有に使えるのですが、併用するメリットはありますか?例えば:mmapmunmapshmmmap
このコード
int main( ) {
int size = 1024;
char* name = "test";
int fd = shm_open(name, O_RDWR|O_CREAT|O_TRUNC, 0600 );
ftruncate(fd, size);
char *ptr = (char *) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (fork()) { // parent
ftruncate(fd, size); // cut the file to a specific length
char* msg = (char*)malloc(50*sizeof(char));
sprintf(msg, "parent process with id %d wrote this in shared memory",getpid()); // copy this in msg
strcpy((char*)ptr,msg); // copy msg in ptr (the mmap)
munmap(ptr,size); // parent process no longer has access to this memory space
shm_unlink(name); // parent process is no longer linked to the space named "test"
} else {
sleep(0.00001);
printf("Inside child process %d : %s\n", getpid(), ptr);
munmap(ptr,size);
exit(0);
}
}
出力します
Inside child process 5149 : parent process with id 5148 wrote this in shared memory
fd を削除して -1 に置き換え、フラグを追加するとMAP_ANONYMOUS、
int main( ) {
int size = 1024;
char* name = "test";
char *ptr = (char *) mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (fork() != 0) { // parent
char* msg = (char*)malloc(50*sizeof(char));
sprintf(msg, "parent process with id %d wrote this in shared memory",getpid()); // copy this in msg
strcpy((char*)ptr,msg); // copy msg in ptr (the mmap)
munmap(ptr,size); // parent process no longer has access to this memory space
} else {
sleep(0.00001);
printf("Inside child process %d : %s\n", getpid(), ptr);
munmap(ptr,size);
exit(0);
}
}
出力は変わりません。では、なぜ shm_get を使用するのでしょうか。
ありがとう