Skip to content

Instantly share code, notes, and snippets.

@msymt
Created July 23, 2022 07:07
Show Gist options
  • Save msymt/1ada1a0312ebe8193aba367352c6bdd3 to your computer and use it in GitHub Desktop.
Save msymt/1ada1a0312ebe8193aba367352c6bdd3 to your computer and use it in GitHub Desktop.
C# to C IPC with memory mapped file
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd;
int index;
char *data;
const char *filepath = "/tmp/sharedfile";
if ((fd = open(filepath, O_CREAT|O_RDWR, (mode_t)00700)) == -1) {
perror("open");
exit(EXIT_FAILURE);
}
data = mmap(NULL, 12288, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
for (index= 0; index < 4; index++) {
fprintf(stdout, "%c", data[index]);
}
sleep(10);
if (msync(data, 12288, MS_SYNC) == -1) {
perror("Error sync to disk");
}
if (munmap(data, 12288) == -1) {
close(fd);
perror("Error un-mmapping");
exit(EXIT_FAILURE);
}
close(fd);
return 0;
}
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace FileSharedMemory
{
class MainClass
{
public static void Main (string[] args)
{
using (var mmf = MemoryMappedFile.CreateFromFile("/tmp/sharedfile", FileMode.OpenOrCreate, "/tmp/sharedfile"))
{
using (var stream = mmf.CreateViewStream ()) {
Console.WriteLine("Start.");
// writing "Test" at the beginning of memory-mapped file.
stream.Position = 0;
var buffer = new byte[] { 0x54, 0x65, 0x73, 0x74 }; // Test
stream.Write (buffer, 0, 4);
Thread.Sleep (20000);
Console.WriteLine("End.");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment