Saturday, April 23, 2022

Share large allocated memory across applications without duplication


In some client - server applications running on same box,  a large amount of data may need to be shared. For example, an image acquisition application sharing the image with its clients. This typically involves using file Mapping objects to share memory across processes. However sometimes this can be overbearing if only two processes are involved.  Instead ReadProcessMemory and WriteProcessMemory APIs can be used.
What this means is a Process A can share its array with Process B without doing  IPC except sharing its PID and address of the array. Debuggers exploit this..

In the demo below, Writer process fills an array and shares it with Reader process. The array is read by the reader process using  ReadProcessMemory api . Also the array is repopulated using WriteProcessMemory api and is available to Writer process.





Sequence

Reader process starts
Writer process starts

Writer Process: 
creates an array of 100000  in writer process
Writes 100000 bytes containing 1
signals Reader with process handle and array memory address
sleeps for 5 seconds

Reader Process: 
Opens array using writer process handle and array memory address
Reads 100000 bytes containing 1
Writes 100000 bytes containing 2

Writer Process: 
Reads 100000 bytes containing 2

Source and Binaries can be found here.


No comments:

Post a Comment