Reputation: 19893
I'm writing a C++ app that will communicate with another process via boost::interprocess, however I need to check if the other process is actually running first - as the other process is responsible for creating the inter-process shared memory. How do I check if the other process is running ?
folks, I'm specifically required to check other processes
Upvotes: 2
Views: 5637
Reputation: 94529
The managed_shared_memory ctor will throw an interprocess_exception in case it fails to open the given shared memory (assuming you passed open_only to the ctor). You could use the error code in the exception to test whether the shared memory is available or not.
All means to check whether a process is running (by looking at the process tree, testing for magic log files or whatever) suffer from a race condition which occurs if the remote process is running, but it didn't yet manage to setup the shared memory.
Update: If you only want to check whether a process is being executed by the operating system, then you need to walk the list of processes and consider each one. Here you can find an example how to do that.
A much easier, more portable, but less precise technique is to use lock files. Process A creates a magic 'lock file' in some location on startup, and deletes it as it terminates. Process B can then test for the existence of this file to determine whether Process A is running. A null-byte size file would be sufficient for this, but the file could also contain additional information which is helpful to Process B (such as the PID of Process A). However, there's a short time window at the very beginning of Process A at which no lock file exists - yet the process is running.
Upvotes: 2
Reputation: 2272
you can either use mutex or try to open the shared memory file and handle the exception.
Upvotes: 1