gpt4 book ai didi

c - mmap 缓冲区到文件句柄

转载 作者:IT王子 更新时间:2023-10-29 01:40:10 24 4
gpt4 key购买 nike

我需要“伪造”一个文件描述符(支持 fstat),我是这样做的。

func ScanBytes(b []byte) error {
size := C.size_t(len(b))
path := C.CString("/bytes")
fd := C.shm_open(path, C.O_RDWR|C.O_CREAT, C.mode_t(0600))
defer C.shm_unlink(path)
defer C.close(fd)

res := C.ftruncate(fd, C.__off_t(size))
if res != 0 {
return fmt.Errorf("could not allocate shared memory region (%d)", res)
}

var addr = unsafe.Pointer(&b[0])
C.mmap(addr, size, C.PROT_READ|C.PROT_WRITE, C.MAP_SHARED|C.MAP_FIXED, fd, 0)
defer C.munmap(addr, size)

// _, err := syscall.Write(int(fd), b)

return doSomethingWith(fd)
}

您会看到写入文件句柄的地方被注释掉了。

如果我不将缓冲区写入分配的区域,它就是空的。我希望 mmapMAP_FIXED 一起使用所提供缓冲区的地址,从而将内容映射到该区域。

我猜 write 调用复制,从而使内存使用量加倍。我真的必须编写吗?

最佳答案

听起来您想要的是能够通过文件描述符访问现有内存区域而无需复制。

这个问题听起来很像 this previous stackoverflow question about mmap .

那里的答案没什么可补充的。如果您不控制 b 的分配,那么没有副本是不可能做到这一点的。接受需要副本,您的 shm 解决方案很好。不需要 mmap。

从 mmap 的手册页中,MAP_FIXED 的定义:

Do not permit the system to select a different address than the one specified. If the specified address cannot be used, mmap() will fail. If MAP_FIXED is specified, addr must be a multiple of the pagesize. If a MAP_FIXED request is successful, the mapping established by mmap() replaces any previous mappings for the process' pages in the range from addr to addr + len. Use of this option is discouraged.

很有可能 unsafe.Pointer(&b[0]) 不是页面大小的倍数,尤其是在底层数组很小的情况下。 mmap 在那种情况下会失败。与往常一样,检查返回值

如果 mmap 确实成功,映射将替换任何以前的映射,这意味着您的数据现在已经消失了。读取 slice 会给你归零字节。

关于c - mmap 缓冲区到文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com