Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an inheritable Semaphore in .NET?

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.

like image 965
pauldoo Avatar asked Jan 01 '26 04:01

pauldoo


1 Answers

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).

like image 118
Reed Copsey Avatar answered Jan 06 '26 01:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!