【问题标题】:Cannot create a semaphore as standard user on Windows 7无法在 Windows 7 上以标准用户身份创建信号量
【发布时间】:2013-01-25 21:46:39
【问题描述】:

我不知道这是否是设计使然,但我似乎无法以标准用户或高级用户的身份在 Windows 7 上创建新的信号量。

SemaphoreSecurity semSec = new SemaphoreSecurity(); 

// have also tried "Power Users", "Everyone", etc. 
SemaphoreAccessRule rule = new SemaphoreAccessRule("Users", SemaphoreRights.FullControl, AccessControlType.Allow);   

semSec.AddAccessRule(rule);

bool createdNew = false;

// throws exception 
sem = new Semaphore(1, 1, SEMAPHORE_ID, out createdNew, semSec);  

return true; 

我收到了一个 UnauthorizedAccessException 消息“访问端口被拒绝。”

这可能吗?

【问题讨论】:

  • 我相信,在所有这些中,只有互斥锁可以在进程间工作。而且互斥锁并没有发出我需要的信号——任何线程都可以在信号量上调用release(),而使用互斥锁,只有获得锁的线程才能释放它,并且没有计数机制。

标签: c# .net windows-7 synchronization semaphore


【解决方案1】:

MSDN documentation on that topic,好像解决的办法是设置Semaphore创建的安全级别。

这是给定链接的源代码摘录:

// The value of this variable is set by the semaphore 
// constructor. It is true if the named system semaphore was 
// created, and false if the named semaphore already existed. 
// 
bool semaphoreWasCreated;

// Create an access control list (ACL) that denies the 
// current user the right to enter or release the  
// semaphore, but allows the right to read and change 
// security information for the semaphore. 
// 
string user = Environment.UserDomainName + "\\" 
    + Environment.UserName;
SemaphoreSecurity semSec = new SemaphoreSecurity();

SemaphoreAccessRule rule = new SemaphoreAccessRule(
    user, 
    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
    AccessControlType.Deny);
semSec.AddAccessRule(rule);

rule = new SemaphoreAccessRule(
    user, 
    SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
    AccessControlType.Allow);
semSec.AddAccessRule(rule);

// Create a Semaphore object that represents the system 
// semaphore named by the constant 'semaphoreName', with 
// maximum count three, initial count three, and the 
// specified security access. The Boolean value that  
// indicates creation of the underlying system object is 
// placed in semaphoreWasCreated. 
//
sem = new Semaphore(3, 3, semaphoreName, 
    out semaphoreWasCreated, semSec);

// If the named system semaphore was created, it can be 
// used by the current instance of this program, even  
// though the current user is denied access. The current 
// program enters the semaphore. Otherwise, exit the 
// program. 
//  
if (semaphoreWasCreated)
{
    Console.WriteLine("Created the semaphore.");
}
else
{
    Console.WriteLine("Unable to create the semaphore.");
    return;
}

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    经过更多的研究和尝试,我终于解决了这个问题,

    关键是在信号量名称前加上“Global\”,即,

        const string NAME = "Global\\MySemaphore"; 
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      相关资源
      最近更新 更多