gpt4 book ai didi

c - shm_open() 和 ftruncate() 的用途?

转载 作者:IT王子 更新时间:2023-10-29 00:11:57 26 4
gpt4 key购买 nike

当我们创建共享内存时,我们使用 shm_open()ftruncate() 函数。根据我的信息,shm_open() 创建一个共享内存区域。然后我们使用 ftruncate() 函数来配置共享内存区域的大小。

shm_open() 在不知道大小的情况下如何首先创建内存区域?如果情况并非如此,我完全错了,那么请告诉我 shm_open()ftruncate() 的目的。提前致谢!!!

最佳答案

shm_open 的要点是您可以打开一个现有 内存区域。然而,如果它不存在而您要创建它,shm_open 将创建一个新的 0 字节共享内存对象,就像使用 O_CREATopen 会创建一个 0 字节的文件。来自 Linux manuals :

O_CREAT

Create the shared memory object if it does not exist. The user and group ownership of the object are taken from the corresponding effective IDs of the calling process, and the object's permission bits are set according to the low-order 9 bits of mode, except that those bits set in the process file mode creation mask (see umask(2)) are cleared for the new object. A set of macro constants which can be used to define mode is listed in open(2). (Symbolic definitions of these constants can be obtained by including .)

A new shared memory object initially has zero length--the size of the object can be set using ftruncate(2). The newly allocated bytes of a shared memory object are automatically initialized to 0.

(强调我的)

由于 shm_open 不将新创建区域的大小作为参数(这会使系统调用/库调用复杂化,以便为各种情况添加参数),ftruncate( ) 必须用于更改打开的共享内存区域的初始大小。


当然,对于已经在别处正确创建和调整大小的共享内存段,您不必使用 ftruncate。如果您想知道它的大小,请使用 fstat。另见 shm_overview(7)

关于c - shm_open() 和 ftruncate() 的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36055796/

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