text exchange between two processes on a box using Memory Mapped File

831 views Asked by At

Requirement is to be able to achieve 'chat' like communication between two console apps on the same windows box. I implemented this using named pipes, by implementing both a sender and receiver functionality in each app.

I want to try the same functionality but using Memory Mapped files (though I think it is not ideal for 'chat' type communication).

For simplicity sake, say chat messages are just strings of short length.

Here is what I have in mind:

One app will take care of creating a mutex and the memory mapped file. Call it master.

In each app, we maintain two threads, one responsible for taking user input and writing to the file, the other responsible for periodically checking if it has something to read.

So four threads in all, each governed by a mutex for access to the file.

Within the file, I think both should have their own 'section'. say first half of the file size is for master app and the other half for the second app.

So when user inputs a line of text in master app, the thread accesses its half of the file and tries to append new text after the last new line.

When app reads its section of the file for text, if there is any, app reads it and blanks out its section.

Is this approach correct? Other approach would be to some how mark the message with the source id, so that the reader knows to ignore messages that are written by itself. But I feel that is unnecessary string parsing.

Also, other than each reader thread periodically trying to read their section of the file to see if there is new data, can you suggest any kind of notification mechanism? Sort of event handling? Reader thread will only go look for new messages if it gets some kind of event notification.

Any thoughts?

1

There are 1 answers

0
Yaur On

I agree with Hans for the most part, memory mapped files would not nessecarily be ideal here, if you go down this road though consider using a named event (see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx) instead of polling.

You may need to p/invoke to get at this functionality from c#.

On the rest give each app its own region of the file, with a control section managed by the master to coordinate who gets what.