什么阻止我读/写超过共享内存的大小?(系统 V IPC) [英] What stops me from reading/writing further than the size of a shared memory? (System V IPC)

查看:37
本文介绍了什么阻止我读/写超过共享内存的大小?(系统 V IPC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的是:

shmget(shm_key, shm_size, 0666 | IPC_CREAT);(当然还有附加)

而且我已经将大小设置为恰好 12 字节,但是当我尝试以下操作时:

sprintf(shm_ptr, "想象一下这里有 200-300 个字符\n");

它似乎在零问题或警告的情况下正常工作,为了检查,我尝试从一个完全不同的进程(我分叉并执行第一个进程)读取它,果然>

printf("%s", shm_ptr);

打印该段中的消息,应该是 12 字节.System V IPC 应该是这样的,并且没有解决该问题的方法吗?如果是这样,为什么首先要设置大小?

感谢您的时间和提前回答.

解决方案

没有什么能阻止你,但规范不保证这种情况下的任何特定行为.

实际上,内存区域的实际大小将四舍五入为系统特定的页面大小.这使得访问比请求更多的内存成为可能,但可能会产生后果.例如,内存清理器可能会将其视为错误.

这适用于所有内存映射,包括使用 mmap 创建的那些.

现在,为什么需要访问超出请求区域的内存?如果您需要更多内存,只需请求更多.让内存消毒剂不会因意外行为而发疯是一件非常有用的事情.除此之外,我认为这没有任何后果,至少我无法想出任何东西.

如果要查找代码中的访问错误,可以在内存块的末尾放置一个保护页".只需额外分配一页内存并使用mprotect 将其访问权限更改为PROT_NONE.这样,如果超出映射范围(但不超过 1 页),就会出现段错误.

What I'm doing is:

shmget(shm_key, shm_size, 0666 | IPC_CREAT); (and of course attach to it)

and I've already set the size to exactly 12 Bytes but when i try something like:

sprintf(shm_ptr, "Imagine about 200-300 characters here\n");

it seems to work normally with zero problems or warnings, and to check that, I tried to read it from a completely different process (i fork and exec the first one) and sure enough

printf("%s", shm_ptr);

prints the message that was in that segment, which is supposed to be 12 Bytes. Is System V IPC supposed to be like this, and there is no workaround for that issue? If so, why set a size in the first place?

Thanks for your time and answers in advance.

解决方案

Nothing stops you, but the spec does not guarantee any specific behavior for this case.

In practice, the actual size of a memory region will be round up to a system-specific page size. This makes it possible to access more memory than was requested, but there might be consequences. For example, memory sanitizers might treat this as an error.

This is true for all memory mapping, including those created with mmap.

Now, why do you need to access memory beyond requested region? If you need more memory, just request more. Having memory sanitizers not going crazy due to unexpected behavior is a very useful thing. Other than that, I don't think there are any consequences to this, at least I cannot come up with anything atm.

EDIT: If you want to find access errors in your code, you can put a single "guard page" at the end of your memory block. Just allocate one additional page of memory and use mprotect to change its access rights to PROT_NONE. This way you will get segfault if you go beyond your mapping (but no more than 1 page).

这篇关于什么阻止我读/写超过共享内存的大小?(系统 V IPC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆