Ftruncate failed a second time

I am trying to surpass a shared memory object after shm_open and ftruncate successfully on fisrt. Here is the code

char *uuid = GenerateUUID(); int fd = shm_open(uuid, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR); if(fd == -1) perror("shm_open"); size_t shmSize = sizeof(container); int ret = ftruncate(fd, shmSize); perror("ftruncate first"); ret = ftruncate(fd, shmSize * 2); perror("ftruncate second"); 

It can pass the first ftruncate, but for the second ftruncate it exceeds the unsuccessful with errno = 22, "Invalid argument".

I also tried to take a picture of the memory object after mmap, refer to the ftruncate man page, the shared memory should be formatted as zero to the new length.

In addition, I also tried to photograph the memory object in the child process (this is an IPC topic among two processes), ftruncate returns "Invalid fd, no such file or directory", but I could shm_open and mmap successfully in the child process.

Any ideas? Thanks!

+1
source share
2 answers

I think this is the famous "function" shm_open (), ftruncate (), mmap (). You must first ftruncate () to give shared memory a length, but in subsequent moments ftruncate () gives this errno 22, which you can simply ignore. See http://lists.apple.com/archives/darwin-development/2003/Oct/msg00187.html

take away

0
source

The implementation used seems to conform to the older specification , where returning an error is a valid behavior for ftruncate(fd, length) when length exceeds the previous length:

If the file was previously smaller than this size, ftruncate () should either increase the file size or fail.

0
source

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


All Articles