Program mutual exclusion operation in VC ++

zhaozj2021-02-11  232

Program mutual exclusion operation in VC

During the development of the software, sometimes you need to control some programs that cannot be run at the same time, that is, multiple programs mutually exclusive operation (also including multiple instances that are prohibited from running the same program). For this issue, we use the memory map file in Visual C 6.0 to implement mutual exclusive operation between multiple programs.

Before telling the specific programming method, let's first take a look at several important functions related to the memory map file:

1) CREATEFILEMAPPING Function Creates a file mapping object for the specified file, the prototype of the function is as follows:

Handle CreateFilemapping

Handle Hfile, / / ​​File handle for mapping

LPSecurity_Attributes LPFileMappingAttributes, // Safety Descriptor of Memory Mapping

DWORD flprotect, //

DWORD DWMAXIMUMSIGH,

/ / File mapping object with a maximum length of 32 digits

DWORD DWMAXIMUMSIZELOW,

// Lower 32-bit length

LPCTSTR LPNAME

/ / Specify the name of this memory map file

);

2) MapViewOffile function maps the view of the file to the address space of a process, returns the memory pointer of the LPVOID type, through it, you can directly access the information in the file view:

LPVOID MAPVIEWOFFILE

Handle HfilemappingObjct,

// Map file object handle

DWORD DWDESIREDACCESS, // Access Mode

DWORD DWFILEOFFSETHIGH,

// The file offset address is 32 digits

DWORD DWFILEOFFSETLOW,

// Document offset address low 32 digits

DWORD DWNUMBEROFBYTOMAP

// Map view size

);

In Visual C 6.0, we generate the dialog-based applications in Visual C 6.0, in the initialization phase of the program, add the following code at the beginning of the initInstance function of the CWINAPP, add the following code:

{Handle Hmap = CreateFilemapping (Handle) 0xfffffff, NULL,

Page-READWRITE, 0, 128, "MUTEXRUNING");

IF (hmap == null) // If created failed

{AFXMessageBox ("Creating a memory map file object for mutually exclusive running!",

MB-OK | MB-ICONSTOP);

Return false;}

Else IF (getLastError () == Error-already-exists

{LPVOID LPMEM = MapViewOffile (HMAP, File_Map-Write, 0, 0, 0);

CString str = (char =) LPMEM;

UnmapViewOffile (LPMEM);

CloseHandle (HMAP);

AFXMessageBox (STR, MB-OK | MB-ICONSTOP);

Return false;}

Else

{LPVOID LPMEM = MapViewOffile (HMAP, File-Map-Write, 0,0,0);

Strcpy (CHAR ) LPMEM, "XXX program is running!");

UnmapViewOffile (LPMEM);

}

AFXENABLECONTROLCONTAINER ();

......

Here you can call before the initInstance function last returnfalse

CloseHandle (HMAP);

Turn off the memory mapping file object handle Return False;

}

The above procedures have been commissioned in Visual C 6.0.

转载请注明原文地址:https://www.9cbs.com/read-4534.html

New Post(0)