0

我不知道这是否是设计使然,但我似乎无法以标准用户或高级用户的身份在 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消息“拒绝访问端口”。

这可能吗?

4

2 回答 2

0

查看有关该主题的 MSDN 文档,似乎解决方案是为信号量创建设置安全级别。

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

// 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;
}

希望这可以帮助!

于 2013-01-25T22:01:58.267 回答
0

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

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

    const string NAME = "Global\\MySemaphore"; 

谢谢。

于 2013-01-26T01:30:23.447 回答