如何在 .NET 中创建可继承的信号量?
我正在尝试创建一个可继承的 Win32 Semaphore 对象。这意味着我启动的任何子进程都可能自动有权对同一个 Win32 对象进行操作。
我的代码目前如下所示:
Semaphore semaphore = new Semaphore(0, 10);
Process process = Process.Start(pathToExecutable, arguments);
但是此代码中的信号量对象不能被子进程使用。
我正在编写的代码是 C++ 的一个端口。旧的 C++ 代码通过以下方式实现此目的:
SECURITY_ATTRIBUTES security = {0};
security.nLength = sizeof(security);
security.bInheritHandle = TRUE;
HANDLE semaphore = CreateSemaphore(&security, 0, LONG_MAX, NULL);
然后,当调用 CreateProcess
时,bInheritHandles
参数设置为 TRUE
。
(在 C# 和 C++ 情况下,我都使用相同的子进程(即 C++)。它在命令行上获取信号量 ID,并直接在对 ReleaseSemaphore
的调用中使用该值。
)怀疑我需要构造一个特殊的 SemaphoreSecurity
或 ProcessStartInfo
对象,但我还没有弄清楚。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是仅包装创建信号量并启动子进程的 C++ 代码,并通过 P/Invoke(或使用 C++/CLI)调用它。
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).
您可以直接PInvoke到CreateSemaphore和ReleaseSemaphore,只需记住使用与CreateSemaphore的第四个参数相同的名称即可。
You can just PInvoke to CreateSemaphore and ReleaseSemaphore, just remember to use the same name as the forth parameter of CreateSemaphore.