Ejemplo n.º 1
0
        public InterProcessLock(string name, TimeSpan timeout)
        {
            bool created;
            var  security = new MutexSecurity();

            security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
            Mutex      = new Mutex(false, name, out created, security);
            IsAcquired = Mutex.WaitOne(timeout);
        }
        public static Mutex CreateMutexWithFullControlRights(string name, out bool createdNew)
        {
            var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var mutexSecurity      = new MutexSecurity();
            var rule = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow);

            mutexSecurity.AddAccessRule(rule);
            return(new Mutex(false, name, out createdNew, mutexSecurity));
        }
Ejemplo n.º 3
0
        public static Mutex GetNamedMutex(string name)
        {
            using (Logger.SuppressFirstChanceExceptionLogMessages())
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    throw new ArgumentNullException(nameof(name), "Argument cannot be empty, null or white space.");
                }

                Mutex namedMutex;

                // Create a mutex name that is specific to an object (e.g., a path and file name).
                // Note that we use GetPasswordHash to create a short common name for the name parameter
                // that was passed into the function - this allows the parameter to be very long, e.g.,
                // a file path, and still meet minimum mutex name requirements.

                // Prefix mutex name with "Global\" such that mutex will apply to all active
                // application sessions in case terminal services is running.
                string mutexName = $"Global\\{Cipher.GetPasswordHash(name.ToLower(), MutexHash).Replace('\\', '-')}";

            #if MONO
                // Mono Mutex implementations do not include ability to change access rules
                namedMutex = new Mutex(false, mutexName, out bool _);
            #else
                bool doesNotExist = false;

                // Attempt to open the named mutex
                try
                {
                    namedMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize | MutexRights.Modify);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    namedMutex   = null;
                    doesNotExist = true;
                }

                // If mutex does not exist we attempt to create it
                if (doesNotExist)
                {
                    try
                    {
                        MutexSecurity security = new MutexSecurity();
                        security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
                        namedMutex = new Mutex(false, mutexName, out bool _, security);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Named mutex exists now but current user doesn't have full control, attempt to open with minimum needed rights
                        namedMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize | MutexRights.Modify);
                    }
                }
            #endif

                return(namedMutex);
            }
        }
Ejemplo n.º 4
0
        private MutexSecurity GetMutexSecurity(WellKnownSidType sid, MutexRights rights, AccessControlType accessControl)
        {
            MutexSecurity      security   = new MutexSecurity();
            SecurityIdentifier identity   = new SecurityIdentifier(sid, null);
            MutexAccessRule    accessRule = new MutexAccessRule(identity, rights, accessControl);

            security.AddAccessRule(accessRule);
            return(security);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create the mutex instance used to singal that one or more listeners are active.
        /// </summary>
        /// <param name="mutexName">The shared mutex name.</param>
        protected static Mutex CreateMutex(String mutexName)
        {
            var securitySettings = new MutexSecurity();
            var createdNew       = false;

            securitySettings.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));

            return(new Mutex(false, mutexName, out createdNew, securitySettings));
        }
Ejemplo n.º 6
0
        private static void StartIfNotRunning()
        {
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var mutex = new Mutex(false, mutexId))
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings  = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(5000, false);
                        if (hasHandle == false)
                        {
                            Console.WriteLine("Instance already running, timeout expired");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                        hasHandle = true;
                    }

                    if (IsService)
                    {
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[]
                        {
                            new Service()
                        };
                        ServiceBase.Run(ServicesToRun);
                    }
                    else
                    {
                        Run();
                    }
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private static bool LaunchInt(string filename)
        {
            string mutexId = "Global\\foxScreenMutex";

            mutex = new Mutex(false, mutexId);

            MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            MutexSecurity   securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            bool hasHandle = false;

            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(100, false);
                    if (hasHandle == false)
                    {
                        mutex = null;
                        return(false);
                    }
                }
                catch (AbandonedMutexException)
                {
                    hasHandle = true;
                }

                uploadOrganizer   = new UploadOrganizer();
                screenshotManager = new ScreenshotManager(uploadOrganizer);

                if (filename != null)
                {
                    if (LoadCredentials())
                    {
                        uploadOrganizer.AddFileUpload(filename);
                    }
                }

                mainFrm = new frmMain();
                Application.Run(mainFrm);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                if (!hasHandle)
                {
                    mutex = null;
                }
                Stop();
            }

            return(true);
        }
Ejemplo n.º 8
0
        internal static unsafe void AcquireReservedMutex(ref bool bHandleObtained)
        {
            SafeWaitHandle handle = null;

            bHandleObtained = false;
            if (Environment.IsW2k3)
            {
                if (s_ReservedMutex == null)
                {
                    Win32Native.SECURITY_ATTRIBUTES security_attributes;
                    MutexSecurity      security = new MutexSecurity();
                    SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    security.AddAccessRule(new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow));
                    security_attributes = new Win32Native.SECURITY_ATTRIBUTES {
                        nLength = Marshal.SizeOf(security_attributes)
                    };
                    byte[] securityDescriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
                    byte * pDest = stackalloc byte[(IntPtr)securityDescriptorBinaryForm.Length];
                    Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
                    security_attributes.pSecurityDescriptor = pDest;
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                    }
                    finally
                    {
                        handle = Win32Native.CreateMutex(security_attributes, false, @"Global\CLR_RESERVED_MUTEX_NAME");
                        handle.SetAsReservedMutex();
                    }
                    int errorCode = Marshal.GetLastWin32Error();
                    if (handle.IsInvalid)
                    {
                        handle.SetHandleAsInvalid();
                        __Error.WinIOError(errorCode, @"Global\CLR_RESERVED_MUTEX_NAME");
                    }
                    Mutex mutex = new Mutex(handle);
                    Interlocked.CompareExchange <Mutex>(ref s_ReservedMutex, mutex, null);
                }
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                }
                finally
                {
                    try
                    {
                        s_ReservedMutex.WaitOne();
                        bHandleObtained = true;
                    }
                    catch (AbandonedMutexException)
                    {
                        bHandleObtained = true;
                    }
                }
            }
        }
 private void InitMutex()
 {
     string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
     string mutexId = string.Format("Global\\{{{0}}}", appGuid);
     this.mutex = new Mutex(false, mutexId);
     MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
     MutexSecurity securitySettings = new MutexSecurity();
     securitySettings.AddAccessRule(allowEveryoneRule);
     this.mutex.SetAccessControl(securitySettings);
 }
        /// <summary>
        /// Method CreateSharedMutex.
        /// </summary>
        /// <param name="mutexName">The mutex name.</param>
        /// <returns>Instance of Mutex.</returns>
        private Mutex CreateSharedMutex(string mutexName)
        {
            MutexSecurity mutexSecurity = new MutexSecurity();

            mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));

            bool createdNew;

            return(new Mutex(false, mutexName, out createdNew, mutexSecurity));
        }
        private MutexSecurity GetMutexSecurity()
        {
            SecurityIdentifier everyone      = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            MutexAccessRule    allowEveryone = new MutexAccessRule(everyone, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow);
            MutexSecurity      mutexSecurity = new MutexSecurity();

            mutexSecurity.AddAccessRule(allowEveryone);

            return(mutexSecurity);
        }
        /// <summary>
        /// Static constructor to set security access for Mutex
        /// </summary>
        static SageIDClientMutex()
        {
            _mutex = new Mutex(false, "TestApp.APIClient.SageIDClientMutex");

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
Ejemplo n.º 13
0
    public static void Main()
    {
        // Create a string representing the current user.
        string user = Environment.UserDomainName + "\\" +
                      Environment.UserName;

        // Create a security object that grants no access.
        MutexSecurity mSec = new MutexSecurity();

        // Add a rule that grants the current user the
        // right to enter or release the mutex and read the
        // permissions on the mutex.
        MutexAccessRule rule = new MutexAccessRule(user,
                                                   MutexRights.Synchronize | MutexRights.Modify
                                                   | MutexRights.ReadPermissions,
                                                   AccessControlType.Allow);

        mSec.AddAccessRule(rule);

        // Add a rule that denies the current user the
        // right to change permissions on the mutex.
        rule = new MutexAccessRule(user,
                                   MutexRights.ChangePermissions,
                                   AccessControlType.Deny);
        mSec.AddAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);

        // Create a rule that grants the current user
        // the right to read permissions on the mutex, and
        // take ownership of the mutex. Use this rule to
        // remove the right to read permissions from the
        // Allow rule for the current user. The inclusion
        // of the right to take ownership has no effect.
        rule = new MutexAccessRule(user,
                                   MutexRights.TakeOwnership |
                                   MutexRights.ReadPermissions,
                                   AccessControlType.Allow);
        mSec.RemoveAccessRule(rule);

        ShowSecurity(mSec);
    }
Ejemplo n.º 14
0
            private Mutex CreateMutex()
            {
                m_mutexname = GetMutexName(m_filename);

                try
                {
                    // Open the mutex.
                    m_mutex = Mutex.OpenExisting(m_mutexname);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    // The named mutex does not exist.
                    MutexSecurity mSec = new MutexSecurity();

                    MutexAccessRule rule = new MutexAccessRule(
                        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                        MutexRights.FullControl, AccessControlType.Allow);
                    mSec.AddAccessRule(rule);

                    bool mutexWasCreated;
                    m_mutex = new Mutex(false, m_mutexname, out mutexWasCreated, mSec);
                }
                catch (UnauthorizedAccessException)
                {
                    // The named mutex exists, but the user does not have the security access required to use it.
                    LogLog.Warn(typeof(FileAppender), "The named mutex exists, but the user does not have the security access required to use it.");
                    try
                    {
                        m_mutex = Mutex.OpenExisting(m_mutexname, MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                        // Get the current ACL. This requires MutexRights.ReadPermissions.
                        MutexSecurity mSec = m_mutex.GetAccessControl();

                        // Now grant the user the correct rights.
                        MutexAccessRule rule = new MutexAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                            MutexRights.FullControl, AccessControlType.Allow);
                        mSec.AddAccessRule(rule);

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

                        LogLog.Debug(typeof(FileAppender), "Updated mutex security.");

                        m_mutex = Mutex.OpenExisting(m_mutexname);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        LogLog.Error(typeof(FileAppender), "Unable to change permissions on mutex.", ex);
                        m_mutex = new Mutex(false, m_mutexname);
                    }
                }

                return(m_mutex);
            }
Ejemplo n.º 15
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly()
                              .GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
            MutexAccessRule allowEveryoneRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl,
                AccessControlType.Allow);
            MutexSecurity securitySettings = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            using Mutex mutex = new Mutex(false, $"Global\\{{{appGuid}}}", out bool _);
            bool hasHandle = false;

            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(5000, false);
                    if (hasHandle == false)
                    {
                        throw new TimeoutException("Timeout waiting for exclusive access");
                    }
                }
                catch (AbandonedMutexException)
                {
#if DEBUG
                    Console.WriteLine("Mutex abandoned");
#endif
                    hasHandle = true;
                }
                _notifyIcon = new NotifyIcon();
                ContextMenuStrip contextMenu = new ContextMenuStrip();
                contextMenu.Items.Add("Settings").Click += OpenSettings;
                contextMenu.Items.Add("Exit").Click     += Exit;
                _notifyIcon.Icon             = Resources.Resizor;
                _notifyIcon.Text             = "Resizor";
                _notifyIcon.ContextMenuStrip = contextMenu;
                _notifyIcon.Visible          = true;
                Kh             = new KeyboardHook();
                Kh.OnKeyPress += KeyDown;
                Ctx            = new NiApplicationContext();
                Application.Run(Ctx);
                Kh.Dispose();
                _notifyIcon.Visible = false;
            }
            finally
            {
                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                }
            }
        }
Ejemplo n.º 16
0
        internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
        {
            bool               flag;
            MutexSecurity      mutexSecurity = new MutexSecurity();
            SecurityIdentifier identity      = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

            mutexSecurity.AddAccessRule(new MutexAccessRule(identity, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
            Mutex mutexIn = new Mutex(false, mutexName, out flag, mutexSecurity);

            SafeWaitForMutex(mutexIn, ref mutex);
        }
Ejemplo n.º 17
0
        private static bool TryCallingLiveProcess()
        {
            var success = false;

            // Commence craziness.
            // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c

            bool isNew;
            var  allowEveryoneRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);

            using (var mutex = new Mutex(false, MutexId, out isNew, securitySettings)) {
                var hasHandle = false;
                try {
                    hasHandle = mutex.WaitOne(3000, false);
                    if (hasHandle == false)
                    {
                        throw new TimeoutException("Timeout waiting for exclusive access.");
                    }

                    try {
                        var name      = Process.GetCurrentProcess().ProcessName;
                        var processes = Process.GetProcessesByName(name);
                        if (processes.Length == 1)
                        {
                            // Since we are the sole process no relaying is possible.
                            return(false);
                        }

                        RelayCommandLine();

                        success = true;
                    } catch (Exception ex) {
                        Logger.Error(ex);
                        success = false;
                    }
                } catch (TimeoutException ex) {
                    Logger.Error(ex);
                } catch (AbandonedMutexException ex) {
                    Logger.Error(ex);
                    hasHandle = true;
                } finally {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }

            return(success);
        }
Ejemplo n.º 18
0
        public static void WrapSingleInstance(Action action)
        {
            // https://stackoverflow.com/a/229567/
            string appGuid =
                ((GuidAttribute)Assembly.GetExecutingAssembly().
                 GetCustomAttributes(typeof(GuidAttribute), false).
                 GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            // Need a place to store a return value in Mutex() constructor call
            bool createdNew;

            var allowEveryoneRule =
                new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid
                                                           , null)
                                    , MutexRights.FullControl
                                    , AccessControlType.Allow
                                    );
            var securitySettings = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);

            using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
            {
                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(0, false);
                        if (hasHandle == false)
                        {
                            MessageBox.Show("ClickerFixer is already running! Only a single instance can run.\nClickerFixer can be quit from the system tray icon.");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        hasHandle = true;
                    }

                    action();
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Ejemplo n.º 19
0
        static void Main()
        {
            // change process priority
            Process.GetCurrentProcess().PriorityBoostEnabled = true;
            Process.GetCurrentProcess().PriorityClass        = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

            // single instance code

            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var mutex = new Mutex(false, mutexId))
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings  = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(5000, false);
                        //if (hasHandle == false)
                        //    throw new TimeoutException("Timeout waiting for exclusive access");
                    }
                    catch (AbandonedMutexException)
                    {
                        hasHandle = true;
                    }

                    // Actual application run code here.
                    if (hasHandle)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new FormMain());
                    }
                    else
                    {
                        //MessageBox.Show("Application is already running.");
                    }
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public GlobalMutex(string name)
        {
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            bool createdNew;

            mutex     = new Mutex(false, string.Format(@"Global\{0}", name), out createdNew, securitySettings);
            hasHandle = 0;
        }
Ejemplo n.º 21
0
        public static MutexSecurity MutexSecurity()
        {
            SecurityIdentifier user   = GetEveryoneSID();
            MutexSecurity      result = new MutexSecurity();

            MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify | MutexRights.Delete, AccessControlType.Allow);

            result.AddAccessRule(rule);

            return(result);
        }
Ejemplo n.º 22
0
        public static void Hold(Action onWaitingForMutex = null, int timeoutInMs = 5000)
        {
            Validate.IsTrue(timeoutInMs >= 5000, "Timeout must be at least 5 seconds.");

            using CancellationTokenSource acquireSource = new CancellationTokenSource(timeoutInMs);
            CancellationToken token  = acquireSource.Token;
            Thread            thread = new Thread(o =>
            {
                bool first     = true;
                string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
                string mutexId = $@"Global\{{{appGuid}}}";
                MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                                        MutexRights.FullControl,
                                                                        AccessControlType.Allow
                                                                        );
                MutexSecurity securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                Mutex mutex = new Mutex(false, mutexId, out bool _, securitySettings);
                try
                {
                    try
                    {
                        while (!mutex.WaitOne(100, false))
                        {
                            token.ThrowIfCancellationRequested();
                            if (first)
                            {
                                first = false;
                                onWaitingForMutex?.Invoke();
                            }
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Mutex was abandoned in another process, it will still get acquired
                    }
                }
                finally
                {
                    callerGate.Release();
                    mutexReleaseGate.Wait(-1);
                    mutex.ReleaseMutex();
                }
            });

            mutexReleaseGate.Wait(-1, token);
            callerGate.Wait(0, token);
            thread.Start();

            while (!callerGate.Wait(100, token))
            {
            }
        }
Ejemplo n.º 23
0
        static void Main()
        {
            try {
                ProductName      = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName;
                CurrentDirectory = IOHelper.GetCurrentDir(Assembly.GetExecutingAssembly());
                AppHelper.Log    = new Log(Path.Combine(CurrentDirectory, ProductName + ".log"))
                {
                    InsertDate = true, AutoCompress = true
                };
                AppHelper.Log.ExceptionThrownEvent += (e) => MessageBox.Show(e.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                AppHelper.GUID = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
                string          mutexId = string.Format("Global\\{{{0}}}", AppHelper.GUID);
                bool            createdNew;
                MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                                        MutexRights.FullControl, AccessControlType.Allow);
                MutexSecurity securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                using (Mutex mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) {
                    bool hasHandle = false;

                    try {
                        try {
                            hasHandle = mutex.WaitOne(3000, false);
                            if (hasHandle == false)
                            {
                                MessageBox.Show("Программа уже запущена", ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                return;
                            }
                        }
                        catch (AbandonedMutexException err) {
                            AppHelper.Log.Write("Ошибка синхронизации Mutex: " + err.ToString(), MessageType.Error);
                            hasHandle = true;
                        }

                        Application.Run(new MainForm());
                    }
                    finally {
                        if (hasHandle)
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }
            }
            catch (Exception error) {
                MessageBox.Show(error.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 24
0
        private static MutexSecurity GetMutexSecurity()
        {
            var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var mutexAccessRule    = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow);

            var mutexSecurity = new MutexSecurity();

            mutexSecurity.AddAccessRule(mutexAccessRule);

            return(mutexSecurity);
        }
Ejemplo n.º 25
0
        private void initMutex(string key)
        {
            string mutexId = string.Format("Global\\{{{0}}}", key);

            mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);
        }
Ejemplo n.º 26
0
        internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
        {
            bool               createdNew;
            MutexSecurity      sec         = new MutexSecurity();
            SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

            sec.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));

            Mutex tmpMutex = new Mutex(false, mutexName, out createdNew, sec);

            SafeWaitForMutex(tmpMutex, ref mutex);
        }
Ejemplo n.º 27
0
        private void ClaimMutex()
        {
            // Grant access to everyone
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);

            bool createdNew;

            Mutex = new Mutex(true, _mutexName, out createdNew, securitySettings);
        }
        private static Mutex CreateMutex(string name)
        {
#if IS_NET_FRAMEWORK
            // Concurrent builds could be run under different user accounts, so we need to allow all users to wait on the mutex
            var mutexSecurity = new MutexSecurity();
            mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                            MutexRights.FullControl, AccessControlType.Allow));
            return(new Mutex(false, name, out var _, mutexSecurity));
#else
            return(new Mutex(false, name));
#endif
        }
    private void InitMutex()
    {
        string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        string mutexId = string.Format("Global\\{{{0}}}", appGuid);

        mutex = new Mutex(false, mutexId);
        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings  = new MutexSecurity();

        securitySettings.AddAccessRule(allowEveryoneRule);
        mutex.SetAccessControl(securitySettings);
    }
Ejemplo n.º 30
0
        private static Mutex CreateAppMutex()
        {
            var mutex             = new Mutex(false, mutexGuid.ToString());
            var mutexSecurity     = new MutexSecurity();
            var allowEveryoneRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);

            mutexSecurity.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(mutexSecurity);
            return(mutex);
        }
Ejemplo n.º 31
0
        private void InitMutex(Guid appGuid)
        {
            var mutexId = $"Global\\{{{appGuid}}}";

            _mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
Ejemplo n.º 32
0
    // Mutex code from http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
    public static void PreloadUnmanagedLibraries(string hash, string tempBasePath, IEnumerable<string> libs, Dictionary<string, string> checksums)
    {
        var mutexId = string.Format("Global\\Costura{0}", hash);

        using (var mutex = new Mutex(false, mutexId))
        {
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            var hasHandle = false;
            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(60000, false);
                    if (hasHandle == false)
                        throw new TimeoutException("Timeout waiting for exclusive access");
                }
                catch (AbandonedMutexException)
                {
                    hasHandle = true;
                }

                var bittyness = IntPtr.Size == 8 ? "64" : "32";
                CreateDirectory(Path.Combine(tempBasePath, bittyness));
                InternalPreloadUnmanagedLibraries(tempBasePath, libs, checksums);
            }
            finally
            {
                if (hasHandle)
                    mutex.ReleaseMutex();
            }
        }
    }
Ejemplo n.º 33
0
        static void ThreadFunc()
        {
            bool bCreated = false;
            var user = "******";
            var rule = new MutexAccessRule(user, MutexRights.FullControl, AccessControlType.Allow );
            var mSecurity = new MutexSecurity();
            mSecurity.AddAccessRule(rule);
            
            Mutex m = new Mutex(true, Program.mutex_name, out bCreated, mSecurity);
            if (!bCreated)
            {
                Console.WriteLine("Waiting... {0}", Thread.CurrentThread.ManagedThreadId);
                m.WaitOne();
                Console.WriteLine("Acquired Mutex! {0}", Thread.CurrentThread.ManagedThreadId);
            }

            System.Threading.Thread.Sleep(5 * 1000);

            m.ReleaseMutex();

            m.Close();

        }