Oct 02, 2006

Shared Memory in Mono, 4th session

Mono includes Mono.Unix.Native, so flagging is made easy:

using System;
using System.Runtime.InteropServices;

namespace Mono.Unix.Native
public class SharedMemory
[DllImport("librt", EntryPoint="shm_open", CharSet=CharSet.Auto)]
public static extern IntPtr Open (string name, OpenFlags oflag,
FilePermissions mode_t);

[DllImport("libc", EntryPoint="ftruncate")]
public static extern int FTruncate (IntPtr fildes, int length);

[DllImport("libc", EntryPoint="mmap")]
public unsafe static extern byte* MMap (int addr, int len,
MmapProts prot, MmapFlags flags, IntPtr fildes, int off);

public unsafe static void Main (string []args)
int int_sizeof = sizeof (int) * 22;
SharedMemory m = new SharedMemory ();
IntPtr filedes = SharedMemory.Open ("myregion",
OpenFlags.O_CREAT | OpenFlags.O_RDWR,
FilePermissions.S_IRUSR | FilePermissions.S_IWUSR);
int res = SharedMemory.FTruncate (filedes, int_sizeof);
byte* len = SharedMemory.MMap (0, int_sizeof,
MmapProts.PROT_READ | MmapProts.PROT_WRITE,
MmapFlags.MAP_SHARED, filedes, 0);
Console.WriteLine ("Open: "+filedes+" FTruncate: "+
res+" v "+(len!=null));

Above example is a quick port of the OpenGroup example. There's still missing the "real writing". Compile with:

mcs -unsafe SharedMemory.cs -out:SharedMemory.exe -r:System.dll -r:Mono.Posix.dll

Don't forget to do

ls -la /dev/shm

to see your shared memory mapped file.