title: Creating a new process that's not a child of the creating process
body: <p>I am developing an application in which a number of instances of a process, A, depend on a single instance of a process, B. The idea is that one of the instances of process A starts process B so that all the instances of A can use it. The instances of A are hosted in a 3rd party process and can be torn down (by killing the process tree) at unpredictable points in time. It is therefore vital that process B is not a child of any instance of process A.</p>
  
  <p>I have tried to do this using PInvoke to call CreateProcess, specifying DetachedProcess (0x08) in the creation flags, but this did not work (please see code below).</p>
  
  <pre><code>[DllImport("kernel32.dll")]
  private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
  
  
  public Process LaunchProcess(Path executablePath, string args)
  {
      StartupInfo sInfo = new StartupInfo();
  
      const uint creationFlags = (uint)(CreationFlags.CreateNoWindow | CreationFlags.DetachedProcess);
  
      ProcessInformation pInfo;
      bool success = CreateProcess(executablePath.ToString(), args, IntPtr.Zero, IntPtr.Zero, false, creationFlags, IntPtr.Zero, executablePath.GetFolderPath().ToString(), ref sInfo, out pInfo);
  
      if (!success)
      {
          throw new Win32Exception();
      }
  
      return Process.GetProcessById(pInfo.dwProcessId);
  }
  </code></pre>
  
  <p>I have also read the article at <a href="https://stackoverflow.com/questions/3136154/how-to-create-a-process-that-is-not-a-child-of-its-creating-process">How to create a process that is not a child of it&#39;s creating process?</a>, which suggested using an interim process to start the new process, but I am not keen on this approach as it would complicate the synchronisation around ensuring that only a single instance of process B is started.</p>
  
  <p>Does anyone know of a better way of achieving this?</p>