C 同时使用shm_open和mmap有什么用?

C 同时使用shm_open和mmap有什么用?,c,ipc,shared-memory,mmap,posix-api,C,Ipc,Shared Memory,Mmap,Posix Api,阅读手册后,我了解到shm_open和shm_unlink基本上类似于mmap和munmap,区别在于shm用于系统V而mmap用于POSIX。既然两者都可以用于共享内存,那么将两者结合使用是否有优势?例如: 此代码 int main( ) { int size = 1024; char* name = "test"; int fd = shm_open(name, O_RDWR|O_CREAT|O_TRUNC, 0600 );

阅读手册后,我了解到
shm_open
shm_unlink
基本上类似于
mmap
munmap
,区别在于
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\u 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呢


感谢

shm和所谓的shmget()、shmctl()等等,它是Unix System V的遗留产品。它现在已被弃用。但是shm_open()、shm_unlink()是POSIX。您正在使用sprintf()填充消息缓冲区。但是你在里面写了50多个字符。因此,您有一个缓冲区溢出(您正在破坏内存)。使用安全的snprintf()代替sprintf()。您正在使用浮点数调用sleep()。但是sleep()只接受一个未签名的int。谢谢你指出它。我没有意识到这一点,因为我没有得到编译错误,也没有关于第二种情况的错误,你是对的:没有区别。但这是因为您处于相同的流程层次结构中:父流程与其子流程共享其映射。但是独立的过程呢?无法通过mmap()共享同一内存区域。但是有了shm_open()他们就能成功。所谓“独立过程”,我指的是来自不同程序的过程。