Bellow is the snippet of the code that either opens already created mutex or
creates one that can be open by any process.
The trick here is to set right security attributes for newly created mutex.
Some of the functions used are from native Win32 API - you will need to map
them to your program.
Let me know if you have problems doing so.
private void PrivateConstruct(bool initiallyOwned, string name, out
bool createdNew)
{
// It's faster to first try OpenMutex
int hMutex = OpenMutex(SYNCHRONIZE, 1, ToSystemMutexName(name));
createdNew = false;
if (hMutex == 0)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength =
System.Runtime.InteropServices.Marshal.SizeOf(sa);
sa.bInheritHandle = 1;
sa.lpSecurityDescriptor = 0;
int securityDescriptorSize = 0; // dummy
int result =
ConvertStringSecurityDescriptorToSecurityDescripto r(
"D:(A;NP;0x001f0001;;;WD)", // Grant
MUTEX_ALL_ACCESS to Everyone
SDDL_REVISION_1,
ref sa.lpSecurityDescriptor,
ref securityDescriptorSize);
if (result == 0)
{
throw new Exception("Failure while creating security
descriptor for new mutex");
}
hMutex = CreateMutex(ref sa, initiallyOwned ? 1 : 0,
ToSystemMutexName(name));
createdNew = (Marshal.GetLastWin32Error() !=
ERROR_ALREADY_EXISTS);
LocalFree(sa.lpSecurityDescriptor);
if (hMutex == 0)
{
// If we get here, some sort of unrecoverable error has
presumably occurred.
// However, we will try one last time, in case it was
merely some sort of race condition.
// Note that I do not believe that there is any opening
for a race condition in the above code.
// Nevertheless, we have nothing to lose by giving it
one last try.
hMutex = OpenMutex(SYNCHRONIZE, 1,
ToSystemMutexName(name));
createdNew = false;
if (hMutex == 0)
{
throw new Exception("Unable to create or open
mutex.");
}
}
}
Handle = (IntPtr)hMutex;
}
Sergiy Mesropyan
www.anticipatingminds.com
"Ken Varn" <nospam> wrote in message
news:ej**************@TK2MSFTNGP11.phx.gbl...
I have a named mutex object that is accessed by both an asp.net
application and a Windows executable .net application. The Windows executable runs
under the administrator logon, while the asp.net application runs under
the standard asp.net user account. The problem relates to permissions on
creation of the mutex. If the asp.net application creates the mutex, the
executable cannot access it (access denied error). Likewise, if the
executable creates the named mutex, then the asp.net application cannot
access it.
I know that in MFC you can set a security descriptor for the CMutex object
so that it is created with a set security descriptor level. How is this
done in .NET using .NET mutex object?
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.
EmailID = varnk
Domain = Diebold.com
-----------------------------------