Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I resize Linux shared memory with shmctl?

I have a C++ application that allocates shared memory on a Linux system via shmget(2). The data that I store in the shared memory grows periodically, and I'd like to resize the shared memory in a way analogous to the way realloc() grows regular memory. Is there a way to do this? I found a doc on IBM's site that mentions a SHM_SIZE command, but the Linux and BSD manpages do not have it, even in the Linux-specific sections.

like image 263
David Lobron Avatar asked May 07 '13 16:05

David Lobron


People also ask

What is Shmctl used for?

The shmctl() function allows the caller to control the shared memory segment specified by the shmid parameter. Remove the shared memory segment identifier shmid from the system and destroy the shared memory segment.

What is Shmctl in Linux?

The shmctl() function provides a variety of shared memory control operations on the shared memory segment identified by the argument, shmid. The argument cmd specifies the shared memory control operation and may be any of the following values: IPC_STAT.

What is Linux shared memory?

Shared memory is a feature supported by UNIX System V, including Linux, SunOS and Solaris. One process must explicitly ask for an area, using a key, to be shared by other processes. This process will be called the server. All other processes, the clients, that know the shared area can access it.


1 Answers

Simple answer: there is no easy way.

The reasons are pretty logical. Shared memory is being attached to virtual space of every process individually. Each process has it's own virtuall address space. Each process is free to attach the segment at any (not literally, alignment sets some restrictions) arbitrary address. How can system guarantee that, let's say by extending area by 4MiB, every 'user' of this segment will be able to fit bigget block at the same starting address where the smaller segment previously was?

But you should not give up! You can be creative. You can come up with the idea of having one header segment, where you store information about real payload segment. You can make every process to obey some rules as for example: reattach payload segment when its id, as described somewhere in header segment, does not match the known one.

The advice: I suspect you know this, but never keep pointers to data within shared region, only offset.

I hope you'll have some use of my gibberish.

like image 78
GreenScape Avatar answered Sep 30 '22 04:09

GreenScape