ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Mutex Problem

(1/3) > >>

Codebyte:
Im using RAD Studio... This is the code:


--- ---//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
HANDLE mutex;
try
{
const char mutexname[] = "SingleInstanceProgram";
mutex = OpenMutex(0, false, mutexname);
if(mutex == NULL)
{
mutex = CreateMutex(NULL, true, mutexname);
}
else
{
ShowMessage("Application is already running.");
return 0;
        }
Application->Initialize();
SetApplicationMainFormOnTaskBar(Application, true);
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
ReleaseMutex(mutex);
return 0;
}
//---------------------------------------------------------------------------
Somehow, every time i launched the compiled executable it seems to just recreate the mutex as if it was never created in the first place... Any Ideas?

Jibz:
The default permissions probably allow another process to open the mutex. I have used something along the lines of the following in the past:


--- ---// attempt to create mutex
hMutex = CreateMutex(NULL, FALSE, szMutexName);

// get error state
dwVal = GetLastError();

// check if creating the mutex succeeded
if (dwVal != ERROR_SUCCESS)
{
    // if we got a handle to an already existing object, close it
    if (dwVal == ERROR_ALREADY_EXISTS) CloseHandle(hMutex);

    // exit
    return 0;
}

...

CloseHandle(hMutex);

Codebyte:
works, like a charm! you rock :) ty

Codebyte:
one more thing, kind of irrelevant depending on how you look at it... Is there a windows API call that I could use to close a process that is currently open?

Jibz:
Depends on what you mean by closing a process.

If you mean you have opened a handle to a process, and you want to close that handle, then CloseHandle.

If you mean you are a thread in the process you wish to close, then ExitProcess.

If you mean terminating another process that you are not directly involved in, then TerminateProcess (which is a bit harsh, and you might be better off adding some method of closing the process if you are the one coding it).

Navigation

[0] Message Index

[#] Next page

Go to full version