Creating Shared-Memory for two different processes

So, I'm trying to create a shared-memory segment in a C program, so I can for example write a simple character in it, and read that character from another C program.

I've been trying to use calloc() and malloc() but I do believe this only works for this program's own heap.

Is there another function to do this same thing, but in the RAM memory? Maybe through an hexadecimal value? Or am I wrong and these functions actually reserve memory visible to all processes?

Thanks in advance.

EDIT: -I'm using windows 8. -Language is not restricted to C, can be any other language.

Upvotes: 2

Views: 1573

Answers (2)

IInspectable
IInspectable

Reputation: 51511

There are a number of Interprocess Communications you can choose, when you need to transfer data between isolated processes. Sharing a chunk of memory is typically implemented using file mapping objects.

Setting up a file mapping object requires the following sequence of API calls:

  1. CreateFileMapping: This creates the file mapping object. You can pass a unique name (e.g. string representation of a GUID) to easily access this object from other processes.
  2. MapViewOfFile: Maps a view of a file mapping into the address space of the calling process. At that point, the file mapping object can be used, simply by writing to the memory view.

Using an existing file mapping object from another process requires the following calls:

  1. OpenFileMapping: Opens a handle to an existing file mapping object.
  2. MapViewOfFile: Maps a view of a file mapping into the address space of the calling process. Modifications to memory in the memory view are reflected in all views into that file mapping.

Note that sharing memory through file mappings across processes requires synchronization between those processes. This topic is beyond the scope of this answer. The MSDN provides an introduction to synchronization.


Sample code is available in the MSDN as well: Creating Named Shared Memory.

Upvotes: 2

Chris Dodd
Chris Dodd

Reputation: 126536

There's no standard way of doing this. If you were working on Unix/Linux I would suggest looking at my shared memory malloc implementation, which does work on Cygwin on windows machines, but is really designed for Unix.

Upvotes: 0

Related Questions