Number of instances running
-
As long as your code compiles to an exe, you can do it this way:
-
Add the following lines on top of one of your cpp files:
#pragma data_seg("shared")
LONG g_counter = 0; // This variable is allocated on a page shared between processes...
#pragma data_seg()#pragma comment(linker, "/section:shared,rws")
-
Execute the following instruction as soon as possible at startup of your application:
InterlockedIncrement(&g_counter);
-
Execute the following instruction immediately before exiting from your application:
InterlockedDecrement(&g_counter);
-
When you need the number of instance of your application currently running, use this code:
LONG instances = InterlockedExchangeAdd(&g_counter, 0);
This method works properly only with exe because they are never relocated while loaded; the trick is to create a section whith the read, write and shared attributes and put there a variable used to count the instances. This way that variable is shared between all the instances of your application, and you can use the Interlocked Variable Access[^] functions to safely access the variable. See also data_seg (C/C++)[^] and /SECTION[^] for more details on how this code works.
-