The purpose of shm_open () and ftruncate ()?

When we create shared memory, we use the shm_open() and ftruncate() functions. According to my info shm_open() create a shared memory area. And then we use the ftruncate() function to adjust the size of the shared memory area.

Well, how does shm_open() create a memory area in the first place, when it does not yet know the size? And if this is not so, and I am completely wrong, then please tell me the purpose of shm_open() and ftruncate(). Thanks in Advance !!!

+5
source share
1 answer

The highlight of shm_open is that you can open an existing memory area. However, in case it does not exist and you create , shm_open behaves as open when creating the file; the newly created memory area is 0. From the Linux manual :

O_CREAT

Create a shared memory object if it does not exist. The user and group ownership of the object are taken from the corresponding effective identifiers of the calling process, and the object permission bits are set in accordance with the 9-bit low order mode, except that these bits are set in the process file mode creation mask (see umask (2) ) are cleared for the new object. The set of macros that can be used to determine the mode is indicated in open (2). (Symbolic definitions of these constants can be obtained by including.)

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

(my emphasis)

Since shm_open does not accept the size of the newly created area as an argument (this makes it difficult to call the system call / library to add arguments for all kinds of cases), ftruncate() should be used to resize the open shared memory area from its initial size.


Of course, you do not need to use ftruncate for a shared memory segment that is already correctly created and modified elsewhere. If you want to know its size, use fstat . See Also shm_overview(7)

+8
source

Source: https://habr.com/ru/post/1245220/


All Articles