title: CreateMutex() fails with ERROR_ACCESS_DENIED when called by process spawned by Windows Service
body: <p>I just spent several days tracking down a bug caused by the fact that an unhandled exception was being thrown because a call to ::CreateMutex() failed. Keep in mind <code>CreateMutex()</code> doesn't try to lock the mutex, just to open a handle. <strong>It shouldn't fail even if the mutex already exists</strong>, at least so long as I set bInitialOwner to FALSE, which I did.</p>
  
  <p>But if I call <code>::CreateMutexA(0, 0, "testtesttest123");</code>, from a program spawned by a Windows Service (<code>w3wp.exe</code> is its parent and <code>scvhost.exe</code> is its grand-parent and it runs under <code>IIS APPPOOL\Worker1</code> user-account), then it fails and returns NULL if the mutex has been already created by another process running under <code>IIS APPPOOL\*</code>.</p>
  
  <p>I've created a minimal example that reproduces this problem:</p>
  
  <pre><code>void main()
  {
      HANDLE handle = CreateMutexA(0, 0, "testtesttest123");
      std::string lastError = MyGetLastErrorAsText();
      MyAppendToLog("%p %s\n", handle, lastError.c_str());
      Sleep(INFINITE);
  }
  </code></pre>
  
  <p>I run the executable 2 times by double-clicking from Explorer (normal user account), then cause it to be spawned by a Windows Service, and again run it from Explorer.</p>
  
  <p>This creates the following log:</p>
  
  <pre>C:\Test\ReproduceMutexCrash.exe: 00000034 ERROR_SUCCESS
  C:\Test\ReproduceMutexCrash.exe: 00000034 ERROR_ALREADY_EXISTS
  c:\inetpub\wwwroot\Worker1\ReproduceMutexCrash.exe: 00000034 ERROR_SUCCESS
  c:\inetpub\wwwroot\Worker2\ReproduceMutexCrash.exe: 00000000 ERROR_ACCESS_DENIED
  C:\Test\ReproduceMutexCrash.exe: 00000034 ERROR_ALREADY_EXISTS</pre>
  
  <p>Worker1 here runs under <code>IIS APPPOOL\Worker1</code>, while Worker2 runs under <code>IIS APPPOOL\Worker2</code> user account.</p>
  
  <p>From the log it's obvious that if the mutex is created by a normal user process, this doesn't another prevent another user process or even Windows Service from opening a handle. But if a Windows Service has created a mutex, then <code>::CreateMutex()</code> fails when called by another Windows Service, although user processes can still open a handle without a hitch.</p>
  
  <p>Does anyone know why this happens?</p>
  
  <p><strong>Edit:</strong> I saw that the mutex object is <code>\Sessions\1\BaseNamedObjects\testtesttest123</code> when the process is spawned by Explorer, while it's <code>\BaseNamedObjects\testtesttest123</code> when the process is created by <code>IIS</code>, and the owner is <code>Worker1</code> (the process that first managed to create the mutex).</p>