2

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.

2 Answers2

2

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.
Morten Jensen
  • 5,818
  • 3
  • 43
  • 55
IInspectable
  • 46,945
  • 8
  • 85
  • 181
0

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • +1 if you know you way around on Linux, installing cygwin is a super easy way to get access to a (somewhat) familiar environment. – Morten Jensen Jun 14 '13 at 18:01
  • Don't answer, if you don't have anything useful to contribute. [Interprocess Communications](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365574.aspx) answers this question exhaustively. [File mappings](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365574.aspx#base.using_a_file_mapping_for_ipc) are available on Windows just as well. Why do I have to waste my reputation on answers written by authors with complete lack of background on the subject at hand? – IInspectable Aug 08 '16 at 01:32