views:

83

answers:

2

I am trying to create a Win32 Semaphore object which is inheritable. This means that any child processes I launch may automatically have the right to act on the same Win32 object.

My code currently looks as follows:

Semaphore semaphore = new Semaphore(0, 10);
Process process = Process.Start(pathToExecutable, arguments);

But the semaphore object in this code cannot be used by the child process.


The code I am writing is a port of come working C++. The old C++ code achieves this by the following:

SECURITY_ATTRIBUTES security = {0};
security.nLength = sizeof(security);
security.bInheritHandle = TRUE;
HANDLE semaphore = CreateSemaphore(&security, 0, LONG_MAX, NULL);

Then later when CreateProcess is called the bInheritHandles argument is set to TRUE.

(In both the C# and C++ case I am using the same child process (which is C++). It takes the semaphore ID on command line, and uses the value directly in a call to ReleaseSemaphore.)


I suspect I need to construct a special SemaphoreSecurity or ProcessStartInfo object, but I haven't figured it out yet.

+1  A: 

One option would be to just wrap the C++ code which creates the Semaphore and launches the child process, and call it via P/Invoke (or use C++/CLI).

Reed Copsey
In this case I want a completely managed implementation.
pauldoo
A: 

You can just PInvoke to CreateSemaphore and ReleaseSemaphore, just remember to use the same name as the forth parameter of CreateSemaphore.

Sheng Jiang 蒋晟