Using shared data segment to implement limit EXE single instance running

Source: Internet
Author: User

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

     }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.