检查 POSIX 共享内存对象大小

Check POSIX shared memory object size

有什么方法可以检查 shm_open 返回的文件描述符是否由当前进程创建或更早存在?另外,这样做之后有没有办法检查它的大小?

这是我目前拥有的:

if ((fd = shm_open(SHARED_OBJ_NAME, O_RDWR|O_CREAT, 0777)) == -1)
    die(1, "Failed to open shared object");

fd_size = lseek(fd, 0, SEEK_END);

printf("Shared size: %ld\n", fd_size);

if (fd_size == -1 || fd_size < SHARED_OBJ_SIZE) {
    if (ftruncate(fd, 255) == -1)
        printf("ftruncate failed\n");
    fd_size = lseek(fd, 0, SEEK_END);
}

printf("Shared size: %ld\n", fd_size);

但问题是我总是得到两次 "Shared size: -1",并且 ftruncate 只有在创建对象后立即调用才不会失败。

您可能希望在共享内存的名称上使用 stat(),并传入 struct stat 实例的地址。如果函数成功,您会在结构成员 st_size.

中找到共享内存的大小

来自POSIX documentation on stat()

If the named file is a shared memory object, the implementation shall update in the stat structure pointed to by the buf argument the st_uid, st_gid, st_size, and st_mode fields, [...]


同时在共享内存描述符上调用 lseek() 会导致未指定的行为,因此它可能会导致或不会导致预期的结果,具体取决于代码所在的平台 运行。为了保持代码的可移植性,请不要这样做。

来自POSIX documentation on lseek():

If fildes refers to a shared memory object, the result of the lseek() function is unspecified.