一起使用shm_open和mmap有什么用?

问题描述

阅读手册页后,我了解到shm_openshm_unlink基本上类似于mmapmunmap,不同之处在于shm用于系统V和mmap用于POSIX。由于两者都可以用于共享内存,因此一起使用是否有优势?例如:

此代码

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,MAP_SHARED | MAP_ANONYMOUS,-1,0);

    if (fork() != 0) { // parent
        char* msg = (char*)malloc(50*sizeof(char));
        sprintf(msg,size); // parent process no longer has access to this memory space
    } else {
        sleep(0.00001);
        printf("Inside child process %d :  %s\n",size);
        exit(0);
    }
}

输出不变。那么为什么要使用shm_get?

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...