Programming Previous page   Next Page

Memory Mapping Demo

In this demonstration, two separate MATLAB processes communicate with each other by writing and reading from a shared file. They share the file by mapping part of their memory space to a common location in the file. A write operation to the memory map belonging to the first process can be read from the map belonging to the second, and vice versa.

One MATLAB process (running send.m) writes a message to the file via its memory map. It also writes the length of the message to byte 1 in the file, which serves as a means of notifying the other process that a message is available. The second process (running answer.m) monitors byte 1 and, upon seeing it set, displays the received message, puts it into uppercase, and echoes the message back to the sender.

The send Function

This function prompts you to enter a string and then, using memory mapping, passes the string to another instance of MATLAB that is running the answer function.

Copy the send and answer functions to files send.m and answer.m in your current working directory. Begin the demonstration by calling send with no inputs. Next, start a second MATLAB session on the same machine, and call the answer function in this session. To exit, press Enter.

The answer Function

The answer function starts a server that, using memory mapping, watches for a message from send. When the message is received, answer replaces the message with an uppercase version of it, and sends this new message back to send.

To use answer, call it with no inputs.

Running the Demo

Here is what the demonstration looks like when it is run. First, start two separate MATLAB sessions on the same computer system. Call the send function in one and the answer function in the other to create a map in each of the processes' memory to the common file:

Next, enter a message at the prompt displayed by the send function. MATLAB writes the message to the shared file. The second MATLAB session, running the answer function, loops on byte 1 of the shared file and, when the byte is written by send, answer reads the message from the file via its memory map. The answer function then puts the message into uppercase and writes it back to the file, and send (waiting for a reply) reads the message and displays it:

send writes a second message to the file. answer reads it, put it into uppercase, and then writes the message to the file:


Previous page  Deleting a Memory Map Importing Text Data Next page

© 1994-2005 The MathWorks, Inc.