elast0ny / shared_memory

A Rust wrapper around native shared memory for Linux and Windows
382 stars 51 forks source link

Create mapping or open existing mapping #50

Closed ExpHP closed 4 years ago

ExpHP commented 4 years ago

I have two processes, and don't know which of them will attempt to open the shared memory first. When using CreateFileMapping on windows, this is fine, because the semantics of this function are to attempt to either create a new object or return an existing one. So whichever program makes it there first creates the mapping, and the other opens it.

However, in this crate I only see a function for creating a new mapping (ShmemConf::create), and another function for opening an existing mapping (ShmemConf::open).

How can I recover the original semantics of CreateFileMapping?

elast0ny commented 4 years ago

The crate currently wraps CreateFileMapping by checking for ERROR_ALREADY_EXISTS after creation. If last error is set to that, the crate propagates the error to the caller through ShmemError::MappingIdExists. This allows the caller to handle what it wants to do in either the success/failure case.

Both examples\ show a way to handle this design choice : https://github.com/elast0ny/shared_memory-rs/blob/5c7e0da79497c0964afc898c3e6473b5add68a89/examples/event.rs#L7-L11

Note: The example above uses the filesystem to create a "link" to the OS mapping which will throw the error first if a collision exists. When not using flink(), MappingIdExists will be thrown instead