Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an app that starts another copy of itself, but after the application has started twice it should no longer start. It's a console application.

What I have tried:

I have tried to write this to check if my app is running 2 same proc.

C++
void checkProcNumber(int cc ,const char* procfilename) {

	
	HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	PROCESSENTRY32 p32;
	p32.dwSize = sizeof(p32);
	BOOL hres = Process32First(hsnap, &p32);

	while (hres) {

		if (strcmp(p32.szExeFile, procfilename)==0) {

			cc ++;

		}

		hres = Process32Next(hsnap, &p32);
	}
	CloseHandle(hsnap);
}


And after, this to open the app (in the main)


TCHAR buffer[MAX_PATH] = { 0 };
	GetModuleFileName(NULL, buffer, MAX_PATH);
	string current_path = (buffer);
	ShellExecute(NULL, "open", current_path.c_str(), NULL, NULL, SW_HIDE);


and finally this:

int x = 0;
	checkProcNumber(x, "test.exe");
	if (x == 2) {

		cout << "finish";
                Sleep(1000)
//and other code to exit from app.

	}


The problem is that the application does not start twice, but runs indefinitely
Posted
Updated 2-Oct-20 5:09am

1 solution

C++
int x = 0;
checkProcNumber(x, "test.exe");
if (x == 2) {

The value of x will always be zero, since you do not return anything from checkProcNumber.
Change your code as follows:
C++
int checkProcNumber(const char* procfilename) {
    int cc = 0;
// ...

    return cc;
}

// ...

x = checkProcNumber("test.exe");
if (x > 1) {

// ...
 
Share this answer
 
Comments
CPallini 3-Oct-20 12:44pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900