- From console create file:
dd if=/dev/zero of=/tmp/sharedfile bs=12288 count=1
- The C# program
- The C program
mcs Sender.cs
mono Sender.exe
Start.
End.
# another terminal
gcc -o receiver receiver.c
./receiver
Test
dd if=/dev/zero of=/tmp/sharedfile bs=12288 count=1
mcs Sender.cs
mono Sender.exe
Start.
End.
# another terminal
gcc -o receiver receiver.c
./receiver
Test
#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."); | |
} | |
} | |
} | |
} | |
} |