Mutex.OpenExisting 메서드

정의

이미 있는 경우 지정한 명명된 뮤텍스를 엽니다.

오버로드

OpenExisting(String)

이미 있는 경우 지정한 명명된 뮤텍스를 엽니다.

OpenExisting(String, MutexRights)

이미 있는 경우 지정한 명명된 뮤텍스를 원하는 보안 액세스로 엽니다.

OpenExisting(String)

이미 있는 경우 지정한 명명된 뮤텍스를 엽니다.

public:
 static System::Threading::Mutex ^ OpenExisting(System::String ^ name);
[System.Security.SecurityCritical]
public static System.Threading.Mutex OpenExisting (string name);
public static System.Threading.Mutex OpenExisting (string name);
[<System.Security.SecurityCritical>]
static member OpenExisting : string -> System.Threading.Mutex
static member OpenExisting : string -> System.Threading.Mutex
Public Shared Function OpenExisting (name As String) As Mutex

매개 변수

name
String

다른 프로세스와 공유할 동기화 개체의 이름입니다. 이름은 대/소문자를 구분합니다.

반환

Mutex

명명된 시스템 뮤텍스를 나타내는 개체입니다.

특성

예외

name이 빈 문자열인 경우

-또는-

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다.

name이(가) null인 경우.

이름이 name인 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다. 잘못된 이름 때문에 이 예외가 throw되기도 합니다.

name이 잘못되었습니다. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다. 이름과 일반 접두사인 "Global" 및 "Local"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. HResult 속성에서 자세한 정보를 확인할 수 있습니다.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다. 자세한 내용은 개체 이름을 참조하세요.

name이 너무 깁니다. 길이 제한은 운영 체제나 구성에 따라 달라집니다.

명명된 뮤텍스가 있으나 사용자에게 이를 사용하는 데 필요한 보안 액세스 권한이 없는 경우

예제

다음 코드 예제에서는 액세스 제어 보안을 사용하여 명명된 뮤텍스의 교차 프로세스 동작을 보여 줍니다. 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String) 명명된 뮤텍스가 있는지 테스트합니다.

뮤텍스가 없는 경우 현재 사용자에게 뮤텍스를 사용할 수 있는 권한을 거부하지만 뮤텍스에 대한 읽기 및 변경 권한을 부여하는 초기 소유권 및 액세스 제어 보안으로 만들어집니다.

두 명령 창에서 컴파일된 예제를 실행하는 경우 두 번째 복사본은 호출에서 액세스 위반 예외를 throw합니다 OpenExisting(String). 예외가 catch되고, 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String, MutexRights) 사용 권한을 읽고 변경하는 데 필요한 권한으로 뮤텍스를 엽니다.

사용 권한이 변경되면 뮤텍스를 입력하고 해제하는 데 필요한 권한으로 뮤텍스가 열립니다. 세 번째 명령 창에서 컴파일된 예제를 실행하면 새 권한을 사용하여 실행됩니다.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ mutexName = L"MutexExample4";

      Mutex^ m = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the mutex
      // constructor. It is true if the named system mutex was
      // created, and false if the named mutex already existed.
      //
      bool mutexWasCreated = false;

      // Attempt to open the named mutex.
      try
      {
         // Open the mutex with (MutexRights.Synchronize |
         // MutexRights.Modify), to enter and release the
         // named mutex.
         //
         m = Mutex::OpenExisting( mutexName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The mutex does not exist.
      // (2) The mutex exists, but the current user doesn't
      // have access. (3) The mutex exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The mutex does not exist, so create it.
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // mutex, but allows the right to read and change
         // security information for the mutex.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::ReadPermissions |
                MutexRights::ChangePermissions),
            AccessControlType::Allow );
         mSec->AddAccessRule( rule );
         
         // Create a Mutex object that represents the system
         // mutex named by the constant 'mutexName', with
         // initial ownership for this thread, and with the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in mutexWasCreated.
         //
         m = gcnew Mutex( true,mutexName, mutexWasCreated,mSec );
         
         // If the named system mutex was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the mutex. Otherwise, exit the program.
         //
         if ( mutexWasCreated )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the mutex." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the mutex to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            m = Mutex::OpenExisting( mutexName,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"Updated mutex security." );
            
            // Open the mutex with (MutexRights.Synchronize
            // | MutexRights.Modify), the rights required to
            // enter and release the mutex.
            //
            m = Mutex::OpenExisting( mutexName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine(
               L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // If this program created the mutex, it already owns
      // the mutex.
      //
      if ( !mutexWasCreated )
      {
         // Enter the mutex, and hold it until the program
         // exits.
         //
         try
         {
            Console::WriteLine( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // Attempt to open the named mutex.
        try
        {
            // Open the mutex with (MutexRights.Synchronize |
            // MutexRights.Modify), to enter and release the
            // named mutex.
            //
            m = Mutex.OpenExisting(mutexName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Mutex does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The mutex does not exist.
        // (2) The mutex exists, but the current user doesn't 
        // have access. (3) The mutex exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The mutex does not exist, so create it.

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

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

                Console.WriteLine("Updated mutex security.");

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the mutex
        ' constructor. It is True if the named system mutex was
        ' created, and False if the named mutex already existed.
        '
        Dim mutexWasCreated As Boolean

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' mutex, but allows the right to read and change
            ' security information for the mutex.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim mSec As New MutexSecurity()

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

설명

name 접두사 Global\ Local\ 또는 네임스페이스를 지정할 수 있습니다. Global 네임스페이스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스를 지정하면 네임스페이스가 지정되지 않은 경우에도 기본값으로 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션-로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows 동기화 개체 이름에 대한 자세한 내용은 개체 이름을 참조하세요.

요청된 형식의 동기화 개체가 네임스페이스에 있으면 기존 동기화 개체가 열립니다. 동기화 개체가 네임스페이스에 없거나 다른 형식의 동기화 개체가 네임스페이스에 있으면 throw WaitHandleCannotBeOpenedException 됩니다.

메서드는 OpenExisting 지정된 명명된 시스템 뮤텍스를 열려고 시도합니다. 시스템 뮤텍스가 아직 없는 경우 만들려면 매개 변수가 Mutex 있는 name 생성자 중 하나를 사용합니다.

반환되는 개체가 동일한 명명된 시스템 뮤텍스를 나타내더라도 동일한 값을 사용하는 이 메서드에 대한 name 여러 호출이 반드시 동일한 Mutex 개체를 반환하지는 않습니다.

이 메서드 오버로드는 비트 OR 연산을 사용하여 결합된 메서드 오버로드 및 지정 및 MutexRights.Modify 권한을 호출 OpenExisting(String, MutexRights) 하는 MutexRights.Synchronize 것과 같습니다.

플래그를 MutexRights.Synchronize 지정하면 스레드가 뮤텍스에서 대기할 수 있으며 플래그를 MutexRights.Modify 지정하면 스레드가 메서드를 호출 ReleaseMutex 할 수 있습니다.

이 메서드는 뮤텍스의 소유권을 요청하지 않습니다.

적용 대상

OpenExisting(String, MutexRights)

이미 있는 경우 지정한 명명된 뮤텍스를 원하는 보안 액세스로 엽니다.

public:
 static System::Threading::Mutex ^ OpenExisting(System::String ^ name, System::Security::AccessControl::MutexRights rights);
public static System.Threading.Mutex OpenExisting (string name, System.Security.AccessControl.MutexRights rights);
[System.Security.SecurityCritical]
public static System.Threading.Mutex OpenExisting (string name, System.Security.AccessControl.MutexRights rights);
static member OpenExisting : string * System.Security.AccessControl.MutexRights -> System.Threading.Mutex
[<System.Security.SecurityCritical>]
static member OpenExisting : string * System.Security.AccessControl.MutexRights -> System.Threading.Mutex
Public Shared Function OpenExisting (name As String, rights As MutexRights) As Mutex

매개 변수

name
String

다른 프로세스와 공유할 동기화 개체의 이름입니다. 이름은 대/소문자를 구분합니다.

rights
MutexRights

원하는 보안 액세스 권한을 나타내는 열거형 값의 비트 조합입니다.

반환

Mutex

명명된 시스템 뮤텍스를 나타내는 개체입니다.

특성

예외

name이 빈 문자열인 경우

-또는-

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다.

name이(가) null인 경우.

이름이 name인 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다. 잘못된 이름 때문에 이 예외가 throw되기도 합니다.

name이 잘못되었습니다. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다. 이름과 일반 접두사인 "Global" 및 "Local"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. HResult 속성에서 자세한 정보를 확인할 수 있습니다.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다. 자세한 내용은 개체 이름을 참조하세요.

name이 너무 깁니다. 길이 제한은 운영 체제나 구성에 따라 달라집니다.

명명된 뮤텍스가 있지만 사용자에게 필요한 보안 액세스가 없습니다.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용하여 명명된 뮤텍스의 교차 프로세스 동작을 보여 줍니다. 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String) 명명된 뮤텍스가 있는지 테스트합니다.

뮤텍스가 없는 경우 현재 사용자에게 뮤텍스를 사용할 수 있는 권한을 거부하지만 뮤텍스에 대한 읽기 및 변경 권한을 부여하는 초기 소유권 및 액세스 제어 보안으로 만들어집니다.

두 명령 창에서 컴파일된 예제를 실행하는 경우 두 번째 복사본은 호출에서 액세스 위반 예외를 throw합니다 OpenExisting(String). 예외가 catch되고, 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String, MutexRights) 사용 권한을 읽고 변경하는 데 필요한 권한으로 뮤텍스를 엽니다.

사용 권한이 변경되면 뮤텍스를 입력하고 해제하는 데 필요한 권한으로 뮤텍스가 열립니다. 세 번째 명령 창에서 컴파일된 예제를 실행하면 새 권한을 사용하여 실행됩니다.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ mutexName = L"MutexExample4";

      Mutex^ m = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the mutex
      // constructor. It is true if the named system mutex was
      // created, and false if the named mutex already existed.
      //
      bool mutexWasCreated = false;

      // Attempt to open the named mutex.
      try
      {
         // Open the mutex with (MutexRights.Synchronize |
         // MutexRights.Modify), to enter and release the
         // named mutex.
         //
         m = Mutex::OpenExisting( mutexName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The mutex does not exist.
      // (2) The mutex exists, but the current user doesn't
      // have access. (3) The mutex exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The mutex does not exist, so create it.
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // mutex, but allows the right to read and change
         // security information for the mutex.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::ReadPermissions |
                MutexRights::ChangePermissions),
            AccessControlType::Allow );
         mSec->AddAccessRule( rule );
         
         // Create a Mutex object that represents the system
         // mutex named by the constant 'mutexName', with
         // initial ownership for this thread, and with the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in mutexWasCreated.
         //
         m = gcnew Mutex( true,mutexName, mutexWasCreated,mSec );
         
         // If the named system mutex was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the mutex. Otherwise, exit the program.
         //
         if ( mutexWasCreated )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the mutex." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the mutex to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            m = Mutex::OpenExisting( mutexName,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"Updated mutex security." );
            
            // Open the mutex with (MutexRights.Synchronize
            // | MutexRights.Modify), the rights required to
            // enter and release the mutex.
            //
            m = Mutex::OpenExisting( mutexName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine(
               L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // If this program created the mutex, it already owns
      // the mutex.
      //
      if ( !mutexWasCreated )
      {
         // Enter the mutex, and hold it until the program
         // exits.
         //
         try
         {
            Console::WriteLine( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // Attempt to open the named mutex.
        try
        {
            // Open the mutex with (MutexRights.Synchronize |
            // MutexRights.Modify), to enter and release the
            // named mutex.
            //
            m = Mutex.OpenExisting(mutexName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Mutex does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The mutex does not exist.
        // (2) The mutex exists, but the current user doesn't 
        // have access. (3) The mutex exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The mutex does not exist, so create it.

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

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

                Console.WriteLine("Updated mutex security.");

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the mutex
        ' constructor. It is True if the named system mutex was
        ' created, and False if the named mutex already existed.
        '
        Dim mutexWasCreated As Boolean

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' mutex, but allows the right to read and change
            ' security information for the mutex.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim mSec As New MutexSecurity()

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

설명

name 접두사 Global\ Local\ 또는 네임스페이스를 지정할 수 있습니다. Global 네임스페이스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스를 지정하면 네임스페이스가 지정되지 않은 경우에도 기본값으로 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션-로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows 동기화 개체 이름에 대한 자세한 내용은 개체 이름을 참조하세요.

요청된 형식의 동기화 개체가 네임스페이스에 있으면 기존 동기화 개체가 열립니다. 동기화 개체가 네임스페이스에 없거나 다른 형식의 동기화 개체가 네임스페이스에 있으면 throw WaitHandleCannotBeOpenedException 됩니다.

매개 변수에는 rights 스레드가 MutexRights.Synchronize 뮤텍스에서 대기할 수 있도록 하는 플래그와 스레드가 MutexRights.Modify 메서드를 호출할 수 있도록 하는 플래그가 ReleaseMutex 포함되어야 합니다.

메서드는 OpenExisting 기존의 명명된 뮤텍스를 열려고 시도합니다. 시스템 뮤텍스가 아직 없는 경우 만들려면 매개 변수가 Mutex 있는 name 생성자 중 하나를 사용합니다.

반환되는 개체가 동일한 명명된 시스템 뮤텍스를 나타내더라도 동일한 값을 사용하는 이 메서드에 대한 name 여러 호출이 반드시 동일한 Mutex 개체를 반환하지는 않습니다.

이 메서드는 뮤텍스의 소유권을 요청하지 않습니다.

적용 대상