private static EventWaitHandleSecurity CreateDefaultWaitHandleSecurity() { EventWaitHandleSecurity eventWaitHandleSecurity = new EventWaitHandleSecurity(); eventWaitHandleSecurity.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); return(eventWaitHandleSecurity); }
private static EventWaitHandle CreateEvent(string fullName, Acl acl, bool isSet = false) { EventWaitHandle result = null; try { #if !UWP var security = new EventWaitHandleSecurity(); if (acl != null) { foreach (var identity in acl) { security.AddAccessRule(new EventWaitHandleAccessRule(identity, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow)); } } result = new EventWaitHandle(isSet, EventResetMode.ManualReset, fullName, out bool _, security); #else result = new EventWaitHandle(isSet, EventResetMode.ManualReset, fullName); #endif return(result); } catch { PlatformSpecificDispose(result); throw; } }
/// <summary>Initializes the synchronization objects needed to deal with multiple instances of the same application.</summary> /// <param name="baseName">The base name of the synchronization objects.</param> /// <param name="identity">The identity to be associated to the synchronization objects.</param> void InitializeSynchronizationObjects(string baseName, IdentityReference identity) { string firstInstanceMutexName = baseName + "_FirstInstance"; string serviceInitializationMutexName = baseName + "_ServiceInitialization"; string serviceReadySemaphoreName = baseName + "_ServiceReady"; string signaledToFirstInstanceSemaphoreName = baseName + "_SignaledToFirstInstance"; bool isNew; var eventRule = new EventWaitHandleAccessRule( identity, EventWaitHandleRights.FullControl, AccessControlType.Allow); var eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(eventRule); var mutexRule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow); var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(mutexRule); firstInstanceMutex = new Mutex(false, firstInstanceMutexName, out isNew, mutexSecurity); serviceInitializationMutex = new Mutex(false, serviceInitializationMutexName, out isNew, mutexSecurity); serviceReadySemaphore = new EventWaitHandle( false, EventResetMode.ManualReset, serviceReadySemaphoreName, out isNew, eventSecurity); signaledToFirstInstanceSemaphore = new EventWaitHandle( false, EventResetMode.AutoReset, signaledToFirstInstanceSemaphoreName, out isNew, eventSecurity); }
public static void StartEvent() { // The event does not exist, so create it. // Create an access control list (ACL) that denies the // current user the right to wait on or signal the // event, but allows the right to read and change // security information for the event. // bool wasCreated; string user = GetUser(); EventWaitHandleSecurity EventHandleSec = new EventWaitHandleSecurity(); EventWaitHandleAccessRule rule = SetRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify); EventHandleSec.AddAccessRule(rule); rule = SetRule(user, EventWaitHandleRights.ReadPermissions | EventWaitHandleRights.ChangePermissions); EventHandleSec.AddAccessRule(rule); EventHandle = new EventWaitHandle(true, EventResetMode.AutoReset, EventName, out wasCreated, EventHandleSec); if (wasCreated) { Console.Write("Created the named event."); } else { WriteError("Unable to create the event."); return; } }
private void ConfigureDropListener() { var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new EventWaitHandleAccessRule(sid, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); var security = new EventWaitHandleSecurity(); security.AddAccessRule(accessRule); bool newlyCreated = false; var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "ExtensionsForOneDrive_DataAvailableEvent", out newlyCreated, security); if (!newlyCreated) { throw new InvalidOperationException("Configuration Changed event already exists."); } _changeListenerTask = Task.Factory.StartNew(() => { while (waitHandle.WaitOne()) { GetPublicLinkAndStore(); } }); }
private void InitFields() { try { _RxlDataSet = new RxlDataSet(); _SingleLock = new Dictionary <string, EventWaitHandle>(); foreach (DataTable table in _RxlDataSet.Tables) { bool createdNew = false; string handleName = string.Format("{0}{1}Lock", DefaultApplicationInfo.AbbreviatedApplicationName, table.TableName); EventWaitHandle waitHandle = null; try { waitHandle = EventWaitHandle.OpenExisting(handleName, EventWaitHandleRights.FullControl); } catch { } if (waitHandle == null) { EventWaitHandleSecurity waitHandleSecurity = new EventWaitHandleSecurity(); waitHandleSecurity.SetAccessRule(new EventWaitHandleAccessRule(@"BUILTIN\Administrators", EventWaitHandleRights.FullControl, AccessControlType.Allow)); waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, handleName, out createdNew, waitHandleSecurity); } _SingleLock.Add(table.TableName, waitHandle); } } catch { throw; } }
private EventWaitHandle CreateSignal(string name) { EventWaitHandle result = null; // if (EventWaitHandle.TryOpenExisting(name, out result)) // { // return result; // } // else // { // code from https://stackoverflow.com/questions/2590334/creating-a-cross-process-eventwaithandle // user https://stackoverflow.com/users/241462/dean-harding var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); var security = new EventWaitHandleSecurity(); security.AddAccessRule(rule); bool created; var wh = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created, security); return(wh); // } }
public void EventWaitHandle_Create_BeyondMaxPathLength() { // GetRandomName prevents name collision when two tests run at the same time string name = GetRandomName() + new string('x', Interop.Kernel32.MAX_PATH); EventWaitHandleSecurity security = GetBasicEventWaitHandleSecurity(); EventResetMode mode = EventResetMode.AutoReset; if (PlatformDetection.IsNetFramework) { Assert.Throws <ArgumentException>(() => { CreateEventWaitHandle( initialState: true, mode, name, security, expectedCreatedNew: true).Dispose(); }); } else { using EventWaitHandle created = CreateAndVerifyEventWaitHandle( initialState: true, mode, name, security, expectedCreatedNew: true); using EventWaitHandle openedByName = EventWaitHandle.OpenExisting(name); Assert.NotNull(openedByName); } }
/// <summary> /// Gets the cross process event wait handle. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> private EventWaitHandle GetCrossProcessEventWaitHandle(string name) { if (!name.StartsWith("Global\\")) { name = "Global\\" + name; } EventWaitHandle waitHandle; try { waitHandle = EventWaitHandle.OpenExisting(name, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify); } catch (WaitHandleCannotBeOpenedException) { // Create a rule that allows any authenticated user to synchronise with us var users = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); var security = new EventWaitHandleSecurity(); security.AddAccessRule(rule); bool created; waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, name, out created, security); } return(waitHandle); }
private static bool OnlyOneCopy() { bool isnew; s_setup_mutex = new Mutex(true, SETUP_MUTEX_NAME, out isnew); RestoreEvent = null; try { #if RELEASE RestoreEvent = AutoResetEvent.OpenExisting(EVENT_NAME); RestoreEvent.Set(); return(false); } catch (WaitHandleCannotBeOpenedException) { #endif string user = Environment.UserDomainName + "\\" + Environment.UserName; EventWaitHandleSecurity evh_sec = new EventWaitHandleSecurity(); EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); evh_sec.AddAccessRule(rule); bool was_created; RestoreEvent = new EventWaitHandle(false, EventResetMode.AutoReset, EVENT_NAME, out was_created, evh_sec); } catch (Exception) { } return(true); }
private EventWaitHandle CreateEvent() { // based on http://stackoverflow.com/questions/2590334/creating-a-cross-process-eventwaithandle var security = new EventWaitHandleSecurity(); // allow anyone to wait on and signal this lock security.AddAccessRule( new EventWaitHandleAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, domainSid: null), EventWaitHandleRights.FullControl, // doesn't seem to work without this :-/ AccessControlType.Allow ) ); bool ignored; var @event = new EventWaitHandle( // if we create, start as unlocked initialState: true, // allow only one thread to hold the lock mode: EventResetMode.AutoReset, name: this.lockName, createdNew: out ignored, eventSecurity: security ); return(@event); }
static public EventWaitHandle CreateWaitHandle(string id, bool initState, EventResetMode resetMode, bool allowEveryone) { //EventResetMode.AutoReset: Set()後,不管有無進入WaitOne(),馬上被自動reset EventWaitHandle eventWaitHandle; bool createNew; if (allowEveryone) { //避免跨Process因權限不足產生WinIOError (Access to the path 'id' is denied.) // create a rule that allows anybody in the "Users" group to synchronise with us //var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); EventWaitHandleSecurity evhSec = new EventWaitHandleSecurity(); EventWaitHandleRights rights = EventWaitHandleRights.FullControl;// EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify; EventWaitHandleAccessRule evhAccessRule = new EventWaitHandleAccessRule("Everyone", rights, AccessControlType.Allow); evhSec.AddAccessRule(evhAccessRule); eventWaitHandle = new EventWaitHandle(initState, resetMode, id, out createNew); //eventWaitHandle.SetAccessControl(evhSec); } else { eventWaitHandle = new EventWaitHandle(initState, resetMode, id, out createNew); } return(eventWaitHandle); }
/// <summary> /// Listen for a stop request. /// </summary> private void Listen() { String eventName = String.Format("STOP_COPS_MSGSERVER_{0}", Server.Name); sLogger.Info("Listening for event {0}.", eventName); var users = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow); var security = new EventWaitHandleSecurity(); security.AddAccessRule(rule); bool createdNew = false; EventWaitHandle handle = new EventWaitHandle( false, EventResetMode.AutoReset, eventName, out createdNew, security); handle.WaitOne(); sLogger.Info("Received stop request !"); Server.Stop(); }
// Note: in order to be consistent with other messagings (e.g. TcpMessaging) value 0 for timeouts mean infinite time. public SharedMemoryReceiver(string memoryMappedFileName, bool useExistingMemoryMappedFile, TimeSpan openTimeout, int maxMessageSize, MemoryMappedFileSecurity memmoryMappedFileSecurity) { using (EneterTrace.Entering()) { myOpenTimeout = (openTimeout == TimeSpan.Zero) ? TimeSpan.FromMilliseconds(-1) : openTimeout; myMemoryMappedFileName = memoryMappedFileName; myMaxMessageSize = maxMessageSize; // If true then the listener will not create the new memory shared file but will open existing one. // This is useful for security restrictions if the functionality is used in the windows service. myUseExistingMemoryMappedFile = useExistingMemoryMappedFile; myMemmoryMappedFileSecurity = memmoryMappedFileSecurity; // If the security shall be applied. if (myMemmoryMappedFileSecurity != null) { // Create the security for the WaitHandle sync logic. myEventWaitHandleSecurity = new EventWaitHandleSecurity(); myEventWaitHandleSecurity.SetSecurityDescriptorSddlForm("S:(ML;;NW;;;LW)"); SecurityIdentifier aSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); EventWaitHandleAccessRule anAccessRule = new EventWaitHandleAccessRule(aSid, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow); myEventWaitHandleSecurity.AddAccessRule(anAccessRule); } } }
/// <summary> /// Get the ready handle for the given scenario. /// </summary> /// <exception cref="CacheException"/> public static EventWaitHandle GetReadyWaitHandle(string scenario) { try { var eventName = GetReadyEventName(scenario); #if !FEATURE_CORECLR var ret = new EventWaitHandle(false, EventResetMode.ManualReset, eventName, out bool created); var security = new EventWaitHandleSecurity(); // Allow any client to wait on the event. security.AddAccessRule(EventWaitHandleAccessRules.PublicSynchronizeAccessRule()); // Give full control to current user. security.AddAccessRule(EventWaitHandleAccessRules.CurrentUserFullControlRule()); ret.SetAccessControl(security); #else var ret = new EventWaitHandle(false, EventResetMode.ManualReset); #endif return(ret); } catch (Exception e) { throw new CacheException(e.ToString(), e); } }
public AutoCaptureEngine( IEventAggregator events, [ImportMany] IEnumerable <IImageScanner> imageScanners) { this.events = events; this.imageScanners = imageScanners; this.screenCapture = new ScreenCapture(); var direct3DVersion = Direct3DVersion.Direct3D9SharedMem; CaptureMethod = CaptureMethod.AutoDetect; this.captureConfig = new CaptureConfig() { Direct3DVersion = direct3DVersion }; var security = new MutexSecurity(); security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow)); bool created; sharedMemMutexes = new[] { new Mutex(false, "Global\\DXHookD3D9Shared0", out created, security), new Mutex(false, "Global\\DXHookD3D9Shared1", out created, security) }; var ewsecurity = new EventWaitHandleSecurity(); ewsecurity.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); captureDxWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9Capture", out created, ewsecurity); hookReadyWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9CaptureReady", out created, ewsecurity); }
protected override void ProcessRecord() { base.ProcessRecord(); var secAttrs = new EventWaitHandleSecurity(); SecurityIdentifier sid = WindowsIdentity.GetCurrent().User; var rights = EventWaitHandleRights.Synchronize; var aceType = AccessControlType.Allow; var ace = new EventWaitHandleAccessRule(sid, rights, aceType); secAttrs.AddAccessRule(ace); bool createdNew; var eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, null, out createdNew, secAttrs); bool itWorked = NativeMethods.SetHandleInformation(eventWaitHandle.SafeWaitHandle, HandleFlag.Inherit, HandleFlag.Inherit); if (!itWorked) { throw new Win32Exception(); // uses last win32 error } SafeWriteObject(eventWaitHandle); } // end ProcessRecord()
/// <summary> /// Initializes a new instance of the <see cref="MemoryEventStore"/> class. /// </summary> public MemoryEventStore() { var waitHandleSecuritySettings = new EventWaitHandleSecurity(); waitHandleSecuritySettings.AddAccessRule( new EventWaitHandleAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); var waitHandleCreated = false; this.waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MemoryNotificationService2", out waitHandleCreated, waitHandleSecuritySettings); var mutexSecuritySettings = new MutexSecurity(); mutexSecuritySettings.AddAccessRule( new MutexAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow)); var mutexCreated = false; this.mutex = new Mutex(false, @"Global\MemoryEventStore2Mutex", out mutexCreated, mutexSecuritySettings); this.file = MemoryMappedFile.CreateOrOpen("MemoryEventStore2", 10 * 1024 * 1024 /* 10MB */); // TODO (Cameron): Fix. Serializer.RegisterConverters(new[] { new DateTimeConverter() }); }
private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights) { EventWaitHandleSecurity security = null; // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName)) { security = new EventWaitHandleSecurity(); IdentityReference si; try { si = new NTAccount(_session.ExecutableProcessUserName); } catch (Exception e) { throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e)); } EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule( si, eventRights, AccessControlType.Allow); security.AddAccessRule(rule); } return(security); }
public InterProcessLockedMemoryMappedFileStream(string mapName, long capacity) { _mapName = mapName; const int streamHeaderSize = 1024; _mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity + streamHeaderSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, null, HandleInheritability.Inheritable); _header = _mmf.CreateViewAccessor(0, streamHeaderSize); _mmfstr = _mmf.CreateViewStream(streamHeaderSize, capacity); var id = string.Format("Global\\PLMMFS-ObLock-{0}", mapName); var mutexAccessRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(mutexAccessRule); _objectMutex = new Mutex(false, id); _objectMutex.SetAccessControl(mutexSecurity); _writeSignal = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format("Global\\PLMMFS-Written-{0}", mapName)); var eventSecurity = new EventWaitHandleSecurity(); var eventAccessRule = new EventWaitHandleAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow); eventSecurity.AddAccessRule(eventAccessRule); _writeSignal.SetAccessControl(eventSecurity); _capacity = capacity; }
/// <summary> /// Initializes the security for future events creation. /// </summary> private static void InitializeEventSecurity() { AuthorizedUsers = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); AccessRule = new EventWaitHandleAccessRule(AuthorizedUsers, EventWaitHandleRights.FullControl, AccessControlType.Allow); Security = new EventWaitHandleSecurity(); Security.AddAccessRule(AccessRule); }
public void SetAccessControl(EventWaitHandleSecurity eventSecurity) { if (eventSecurity == null) { throw new ArgumentNullException("eventSecurity"); } eventSecurity.Persist(this.safeWaitHandle); }
public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity) { bool manual = IsManualReset(mode); Handle = NativeEventCalls.CreateEvent_internal(manual, initialState, name, out createdNew); }
internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal) { Namespace = @namespace; Key = key; EventWaitHandleSecurity open = null; MemoryMappedFileSecurity transparent = null; var service = servicePrincpal.FirstOrDefault(); var currentIdentity = WindowsIdentity.GetCurrent(); if (service != null && currentIdentity != null) { open = new EventWaitHandleSecurity(); open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow)); open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow)); transparent = new MemoryMappedFileSecurity(); transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow)); transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow)); } _memoryMappedFile = MemoryMappedFile.CreateNew( MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId), bufferSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, transparent, HandleInheritability.Inheritable); StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite); bool createdNew; ProfilerRequestsInformation = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId), out createdNew, open); InformationReadyForProfiler = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId), out createdNew, open); InformationReadByProfiler = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId), out createdNew, open); DataCommunication = new byte[bufferSize]; PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned); }
public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } handle.SetAccessControl(eventSecurity); }
public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity) { if (eventSecurity == null) { throw new ArgumentNullException(nameof(eventSecurity)); } eventSecurity.Persist(handle.GetSafeWaitHandle()); }
private EventWaitHandleSecurity GetEventWaitHandleSecurity(WellKnownSidType sid, EventWaitHandleRights rights, AccessControlType accessControl) { EventWaitHandleSecurity security = new EventWaitHandleSecurity(); SecurityIdentifier identity = new SecurityIdentifier(sid, null); EventWaitHandleAccessRule accessRule = new EventWaitHandleAccessRule(identity, rights, accessControl); security.AddAccessRule(accessRule); return(security); }
public static EventWaitHandle Create( bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity) { return(new EventWaitHandle(initialState, mode, name, out createdNew, eventSecurity)); }
public void SetAccessControl(EventWaitHandleSecurity eventSecurity) { if (null == eventSecurity) { throw new ArgumentNullException("eventSecurity"); } eventSecurity.PersistModifications(SafeWaitHandle); }
[System.Security.SecuritySafeCritical] // auto-generated public void SetAccessControl(EventWaitHandleSecurity eventSecurity) { if (eventSecurity == null) { throw new ArgumentNullException("eventSecurity"); } Contract.EndContractBlock(); eventSecurity.Persist(safeWaitHandle); }
public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity);
private void ListenerThread(object state) { EventWaitHandle bufferReadyEvent = null; EventWaitHandle dataReadyEvent = null; MemoryMappedFile memoryMappedFile = null; try { bool createdNew; var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(everyone, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow)); bufferReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out createdNew, eventSecurity); if (!createdNew) throw new Exception("Some DbgView already running"); dataReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out createdNew, eventSecurity); if (!createdNew) throw new Exception("Some DbgView already running"); var memoryMapSecurity = new MemoryMappedFileSecurity(); memoryMapSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow)); memoryMappedFile = MemoryMappedFile.CreateNew("DBWIN_BUFFER", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None); bufferReadyEvent.Set(); this.writer.WriteLine("[DbgView] Started."); using (var accessor = memoryMappedFile.CreateViewAccessor()) { byte[] buffer = new byte[4096]; while (dataReadyEvent.WaitOne()) { accessor.ReadArray<byte>(0, buffer, 0, buffer.Length); int processId = BitConverter.ToInt32(buffer, 0); int terminator = Array.IndexOf<byte>(buffer, 0, 4); string msg = Encoding.Default.GetString(buffer, 4, (terminator < 0 ? buffer.Length : terminator) - 4); if (hashSet.Contains(processId)) { if (msg == "CozyDebugOutput HideDebugPrint") { hashSet.Remove(processId); } writer.WriteLine("[{0:00000}] {1}", processId, msg); } else if (msg == "CozyDebugOutput ShowDebugPrint") { hashSet.Add(processId); writer.WriteLine("[{0:00000}] {1}", processId, msg); } bufferReadyEvent.Set(); } } } catch (ThreadInterruptedException) { this.writer.WriteLine("[DbgView] Stopped."); } catch (Exception e) { this.writer.WriteLine("[DbgView] Error: " + e.Message); } finally { foreach (var disposable in new IDisposable[] { bufferReadyEvent, dataReadyEvent, memoryMappedFile }) { if (disposable != null) disposable.Dispose(); } } }