Purpose of shm_open() and ftruncate()?

Asked
Active3 hr before
Viewed126 times

7 Answers

purpose
90%

When we create a shared-Memory we use shm_open() and ftruncate() function. According to my information shm_open() create a shared-memory region. And then we use ftruncate() function to configure the size of shared-memory region. ,Well how does shm_open() creates the memory region in the first place when it doesn't yet know the size? And if this is not the case and I am totally wrong, then please tell me the purpose of shm_open() and ftruncate(). Thanks in Advance!!!,Of course you do not have to use ftruncate for a shared memory segment that is already properly created and resized elsewhere. Should you want to know its size, use fstat. See also shm_overview(7),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.

The main point of shm_open is that you can open an existing memory area. However in the case that it didn't exist and you'd create it, shm_open will create a new shared memory object of 0 bytes, just like open with O_CREAT would create a file of 0 bytes. From Linux manuals:

shm_open

The main point of shm_open is that you can open an existing memory area. However in the case that it didn't exist and you'd create it, shm_open will create a new shared memory object of 0 bytes, just like open with O_CREAT would create a file of 0 bytes. From Linux manuals:

shm_open

The main point of shm_open is that you can open an existing memory area. However in the case that it didn't exist and you'd create it, shm_open will create a new shared memory object of 0 bytes, just like open with O_CREAT would create a file of 0 bytes. From Linux manuals:

open

The main point of shm_open is that you can open an existing memory area. However in the case that it didn't exist and you'd create it, shm_open will create a new shared memory object of 0 bytes, just like open with O_CREAT would create a file of 0 bytes. From Linux manuals:

O_CREAT
load more v
88%

When we create a shared-Memory we use shm_open() and ftruncate() function. According to my information shm_open() create a shared-memory region. And then we use ftruncate() function to configure the size of shared-memory region. ,Well how does shm_open() creates the memory region in the first place when it doesn't yet know the size? And if this is not the case and I am totally wrong, then please tell me the purpose of shm_open() and ftruncate(). Thanks in Advance!!!,Of course you do not have to use ftruncate for a shared memory segment that is already properly created and resized elsewhere. Should you want to know its size, use fstat. See also shm_overview(7),What's the main use of this category

The example will explain better.
Suppose you have following declaration in manifest file:

<service android:name="MyService">
   <intent-filter>
      <action android:name="com.x.y.DOWNLOAD_DATA" />
      <action android:name="com.x.y.UPLOAD_DATA" />
   </intent-filter>
</service>
load more v
72%

For details of in-depth Linux/UNIX system programming training courses that I teach, look here. , HTML rendering created 2021-08-27 by Michael Kerrisk, author of The Linux Programming Interface, maintainer of the Linux man-pages project.

SHM_OPEN(3) Linux Programmer 's Manual            SHM_OPEN(3)
load more v
65%

Get a file descriptor with a call to the open or shm_open function. ,Map the object using the file descriptor with a call to the mmap function. ,Close the object with a call to the close function. ,Unmap the object with a call to the munmap function.

fd = shm_open("all_mine", (O_CREAT | O_EXCL | O_RDWR), 0);
load more v
75%

On implementations that choose to implement memory objects using memory directly, a shm_open() followed by an ftruncate() and close() can be used to preallocate a shared memory area and to set the size of that preallocation. This may be necessary for systems without virtual memory hardware support in order to ensure that the memory is contiguous.,The following code segment demonstrates the use of shm_open() to create a shared memory object which is then sized using ftruncate() before being mapped into the process address space using mmap():,Note that such shared memory objects can actually be implemented as mapped files. In both cases, the size can be set after the open using ftruncate(). The shm_open() function itself does not create a shared object of a specified size because this would duplicate an extant function that set the size of an object referenced by a file descriptor.,On implementations where memory objects are implemented using the existing file system, the shm_open() function may be implemented using a macro that invokes open(), and the shm_unlink() function may be implemented using a macro that invokes unlink().

The following code segment demonstrates the use of shm_open() to create a shared memory object which is then sized using ftruncate() before being mapped into the process address space using mmap():

#include <unistd.h>
#include <sys/mman.h>
...

#define MAX_LEN 10000
struct region {        /* Defines "structure" of shared memory */
    int len;
    char buf[MAX_LEN];
};
struct region *rptr;
int fd;

/* Create shared memory object and set its size */

fd = shm_open("/myregion", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd == -1)
    /* Handle error */;

if (ftruncate(fd, sizeof(struct region)) == -1)
    /* Handle error */;

/* Map shared memory object */

rptr = mmap(NULL, sizeof(struct region),
       PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (rptr == MAP_FAILED)
    /* Handle error */;

/* Now we can refer to mapped region using fields of rptr;
   for example, rptr->len */
...

40%

Community Boards Article Discussions Tech Board General Discussions A Brief History of Cprogramming.com Contests Board Projects and Job Recruitment

#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
int main (void){
  char *data;
  int shmfd=-1;
  pid_t pid;
  shmfd = shm_open("/SHAREDMEM",O_CREAT|O_RDWR,S_IRUSR|S_IWUSR);
  if(shmfd==-1){
    perror("creator:shm_open");
    exit(EXIT_FAILURE);
  }
  if(ftruncate(shmfd,1024)){
    perror("creator:ftruncate");
    exit(EXIT_FAILURE);
  }
  data = mmap(NULL,1024,PROT_READ|PROT_WRITE,
                      MAP_SHARED,shmfd,0);

  pid = fork();
  if(pid==0){
    execv("node1",NULL);
  }else{
    waitpid(pid,NULL,0);
  }

  pid = fork();
  if(pid==0){
    execv("node2",NULL);
  }else{
    waitpid(pid,NULL,0);
  }


  printf("data: %s\n",data);

  close(shmfd);
  munmap(data,1024);
  shm_unlink("/SHAREDMEM");
  return 0;
}
load more v
22%

There are two ways of fixing the problem. The first is to use shm_open(), ftruncate() and mmap() to create a shared memory region and obtain a pointer to it:,Another way is to create a region of anonymous memory and set it as shared via mmap():,The key here is that the semaphore must be in a region of shared memory, even if you’re accessing it from related processes such as a parent and its child.,So what part of this article explains sem_open???? I came looking for some explanation on named semaphores but found the easy unnamed semaphores instead

Going back to Vikram’s example, and reading the sem_init() man page very carefully, the issue seems to be that the semaphore is created on the stack of the parent process. When the child is forked, it gets a copy of the semaphore, not a reference to the parent’s semaphore. Adding a few sleep()’s and printf()’s to the example highlights the problem:

#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

int main(int argc, char **argv)
{
  int fd, i,count=0,nloop=10,zero=0,*ptr;
  sem_t mutex;

  //open a file and map it into memory

  fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
  write(fd,&zero,sizeof(int));
  ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
  close(fd);

  /* create, initialize semaphore */
  if( sem_init(&mutex,1,1) < 0)
    {
      perror("semaphore initilization");
      exit(0);
    }
  if (fork() == 0) { /* child process*/
    for (i = 0; i < nloop; i++) {
      sem_wait(&mutex);
      printf("child entered crititical section: %d\n", (*ptr)++);
      sleep(2);
      printf("child leaving critical section\n");
      sem_post(&mutex);
      sleep(1);
    }
    exit(0);
  }
  /* back to parent process */
  for (i = 0; i < nloop; i++) {
    sem_wait(&mutex);
    printf("parent entered critical section: %d\n", (*ptr)++);
    sleep(2);
    printf("parent leaving critical section\n");
    sem_post(&mutex);
    sleep(1);
  }
  exit(0);
}
load more v

Other "purpose-undefined" queries related to "Purpose of shm_open() and ftruncate()?"