Make sure that your program has only one process instance running there are a number of ways to use the shared data segment method is the easiest and most convenient.
An EXE file has a different segment (section) consisting of several code snippets and several data segments. By default, the operating system creates copies of its own data segments for each process instance in order to ensure that each process instance runs in a secure environment, so that multiple process instances will not affect another process instance because one instance modifies the contents of the data segment. But we can also create shared data segments for EXE so that multiple process instances can share the data segment without having their own copy.
So we can place a variable in the shared data segment to represent the number of instances of the current process, thus example of our goal.
The way to create shared data segments is to use compiler directives:
#pragma data_seg("Shared)
unsigned long g_InstanceCount = 0;
#pragma data_seg()
This creates a shared data segment in the EXE file that contains only a variable g_instancecount, and all process instances can access and modify the variable.
You should then also tell the linker the properties of the data segment:
#pragma COMMENT (linker, "/SECTION:SHARED,RWS")
This code is an additional command to the linker when linking:/section:shared,rws. RWS represents the properties of this data segment: readable (read), writable (write), Shared (Share).
Then at your program entry point you can access g_instancecount to get the number of instances of the current process, for example:
#pragma data_seg("Shared)
unsigned long g_InstanceCount = 0;
#pragma data_seg()
#pragma comment(linker,"/SECTION:Share,RWS")
int main()
{
++g_InstanceCount;
if(g_InstanceCount > 1)
{
exit(0);
}
//your normal code here
}