tags:

views:

1399

answers:

3

Hey all,

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

+1  A: 

you can either use mutex or try to open the shared memory file and handle the exception.

M. Utku ALTINKAYA
Yes, but I'm specifically required to check the running processes
Maciek
@M. Utku: A mutex test is fine if you control both applications, because Mutexs will normally be released if the application which opened them closes. That said, I prefer Frerich's solution, assuming the *normal* case is that both applications are running.
Brian
+2  A: 

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.

Frerich Raabe
If you use lock files beware if process A crashes and leaves it's lock file hanging around.
Ron Warholic
A: 
BOBOB BOB