簡體   English   中英

C到C#(Mono)內存映射文件/ linux中的共享內存

[英]C to C# (Mono) memory mapped files/shared memory in linux

我正在研究一種每秒需要大約20兆的數據的嵌入式系統。 我的低級采集,控制和處理層將其中的大部分轉換為少數幾個重要值,但它也可以幫助最終用戶查看未處理數據的窗口。

我正在使用mod-mono在C#中使用ASP.NET前端。 我希望ASP.NET頁面的服務器端部分能夠輕松地請求最后半秒左右的數據。 C ++代碼具有實時約束,因此我不能使用消息傳遞來響應 - 它可能很容易被太多客戶端或快速刷新的人陷入困境。 我希望它能夠將數據放置在任何數量的C#讀者可以根據需要訪問它的地方。

我正在想象一個共享內存區域,其中包含至少16或32MB數據的滾動緩沖區。 C ++代碼不斷更新它,C#代碼可以隨時查看它。 有辦法處理這個嗎? 我在使用內存映射文件時發現的所有信息似乎都集中在分支一個孩子,而不是讓兩個不相關的進程將它用於IPC - 它是否必須在C#應用程序看到之前到達磁盤(或fs緩存等)它,或兩個程序的內存映射實際上使它們共享相同的頁面?

有沒有辦法在C#中訪問POSIX共享內存對象?

這里,通過內存映射文件,使用C程序和C#程序共享信息(兩個不同的進程)的示例:

  1. 從控制台創建文件:dd if = / dev / zero of = / tmp / sharedfile bs = 12288 count = 1

  2. C#程序:

     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 ()) { // 1. C program, filled memory-mapped file with the 'G' character (200 characters) var data = stream.ReadByte (); while (data != -1) { Console.WriteLine ((char)data); data = stream.ReadByte (); } // 2. We write "Goose" at the beginning of memory-mapped file. stream.Position = 0; var buffer = new byte[] { 0x47, 0x6F, 0x6F, 0x73, 0x65 }; stream.Write (buffer, 0, 5); Thread.Sleep (20000); // 3. C program, filled memory-mapped file with the 'H' character (200 characters) stream.Position = 0; data = stream.ReadByte (); while (data != -1) { Console.WriteLine ((char)data); data = stream.ReadByte (); } } } } } } 
  3. C程序:

     #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 < 200; index++) { data[index] = 'G'; } sleep(10); // We must see 'Goose' at the beginning of memory-mapped file. for (index= 0; index < 200; index++) { fprintf(stdout, "%c", data[index]); } for (index= 0; index < 200; index++) { data[index] = 'H'; } 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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM