CreateViewStream() public method

public CreateViewStream ( ) : System.IO.MemoryMappedFiles.MemoryMappedViewStream
return System.IO.MemoryMappedFiles.MemoryMappedViewStream
コード例 #1
0
ファイル: SharedMemoryMappedFile.cs プロジェクト: kidaa/Pulse
        public Stream IncreaseSize(int value, out long offset)
        {
            lock (_lock)
            {
                while (Interlocked.Read(ref _counter) != 0)
                {
                    if (!Monitor.Wait(_lock, 10000, true))
                        throw new NotSupportedException();
                }

                FileStream file = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                try
                {
                    offset = MathEx.RoundUp(file.Length, 0x800);
                    file.SetLength(offset + value);
                    _mmf = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.Inheritable, false);
                }
                catch
                {
                    file.SafeDispose();
                    throw;
                }

                Interlocked.Increment(ref _counter);
                DisposableStream result = new DisposableStream(_mmf.CreateViewStream(offset, value, MemoryMappedFileAccess.ReadWrite));
                result.AfterDispose.Add(new DisposableAction(Free));
                return result;
            }
        }
コード例 #2
0
ファイル: PEFile.cs プロジェクト: ethanmoffat/PELoaderLib
		private void CreateFileStreams()
		{
			if (_file != null || _fileStream != null)
				throw new InvalidOperationException();

			_file = MemoryMappedFile.CreateFromFile(FileName);
			_fileStream = _file.CreateViewStream();
		}
コード例 #3
0
ファイル: SharedRingBuffer.cs プロジェクト: Moones/OpenEnsage
 public SharedRingBuffer(string name, int size)
 {
     _size = size;
     _memory = MemoryMappedFile.CreateOrOpen(name, size + 1);
     _memoryStream = _memory.CreateViewStream();
     _writer = new BinaryWriter(_memoryStream);
     _reader = new BinaryReader(_memoryStream);
     _writer.Write(char.MinValue);
 }
コード例 #4
0
ファイル: MappedFileBuffer.cs プロジェクト: dremerdt/fo-dicom
        public MappedFileBuffer(byte[] data)
        {
            _file = MemoryMappedFile.CreateNew(Guid.NewGuid().ToString(), data.Length);
            _stream = _file.CreateViewStream();
            _stream.Write(data, 0, data.Length);
            
			//File.WriteAllBytes(_file.Name, data);
			_size = (uint)data.Length;
		}
コード例 #5
0
ファイル: HeurFacade.cs プロジェクト: palexster/ermesReloaded
 public HeurFacade(string mutName, string mmfName, int RegIterations)
 {
     // Time of listening before register
     this.Luogo1 = new Dictionary<string, Network>();
     this.threshold = RegIterations;
     this.mut = Mutex.OpenExisting(mutName); ;
     this.mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.FullControl, HandleInheritability.None);
     this.stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.Read);
 }
コード例 #6
0
 public MemoryMappedFileMessageSender(string name)
 {
     _file = MemoryMappedFile.CreateOrOpen(name, SizeOfFile);
     _bytesWrittenAccessor = _file.CreateViewAccessor(0, SizeOfInt32);
     _messageCompletedAccessor = _file.CreateViewAccessor(SizeOfInt32, SizeOfBool);
     _stream = _file.CreateViewStream(SizeOfInt32 + SizeOfBool + SizeOfBool, SizeOfStream);
     _messageSendingEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageSending");
     _messageReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageRead");
     _messageCancelledEvent = new EventWaitHandle(false, EventResetMode.ManualReset, name + "_MessageCancelled");
     _bytesWrittenEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesWritten");
     _bytesReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesRead");
 }
コード例 #7
0
ファイル: MemoryFileAid.cs プロジェクト: zhangwuhua/ZwhAid4.0
 /// <summary>
 /// 非持久化内存映射文件写入
 /// </summary>
 /// <param name="name"></param>
 /// <param name="capacity"></param>
 /// <param name="en"></param>
 /// <param name="buffer"></param>
 public void Write(string name, Int64 capacity, Encoding en, byte[] buffer)
 {
     using (mmf = MemoryMappedFile.CreateNew(name, capacity, MemoryMappedFileAccess.ReadWrite))
     {
         using (MemoryMappedViewStream mmvs = mmf.CreateViewStream())
         {
             using (BinaryWriter bw = new BinaryWriter(mmvs, en))
             {
                 bw.Write(buffer);
             }
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// Creates a new FileReader instance.
        /// </summary>
        /// <param name="Path">The path of the file to read.</param>
        /// <param name="BigEndian">Is the filed stored as big endian?</param>
        public FileReader(string Path, bool BigEndian)
        {
            m_MemFile = MemoryMappedFile.CreateFromFile(Path, FileMode.Open, Guid.NewGuid().ToString(), 0,
                MemoryMappedFileAccess.Read);

            try
            {
                m_Reader = new BinaryReader(m_MemFile.CreateViewStream(0, 0, MemoryMappedFileAccess.Read));
            }
            catch(IOException Exception)
            {
                throw new ReadingException("Couldn't open file - FileReader.cs\r\n" + Exception.ToString());
            }
        }
コード例 #9
0
ファイル: MemoryFileAid.cs プロジェクト: zhangwuhua/ZwhAid4.0
 /// <summary>
 /// 内存映射文件读取
 /// </summary>
 /// <param name="name">内存映射文件名称</param>
 /// <param name="capacity">内存映射文件大小</param>
 /// <param name="en">编码</param>
 public byte[] Read(string name, Int64 capacity, Encoding en)
 {
     byte[] buffer = new byte[capacity];
     using (mmf = MemoryMappedFile.OpenExisting(name))
     {
         using (MemoryMappedViewStream mmvs = mmf.CreateViewStream())
         {
             using (BinaryReader br = new BinaryReader(mmvs, en))
             {
                 int length = int.Parse(capacity.ToString());
                 br.Read(buffer, 0, length);
             }
         }
     }
     return buffer;
 }
コード例 #10
0
ファイル: FileSegment.cs プロジェクト: kidaa/Pulse
 public FileSegment(MemoryMappedFile mmf, long offset, long length, MemoryMappedFileAccess access)
 {
     _mmf = Exceptions.CheckArgumentNull(mmf, "mmf");
     try
     {
         _length = length;
         if (_length == 0)
             _stream = new MemoryStream();
         else
             _stream = mmf.CreateViewStream(offset, length, access);
     }
     catch
     {
         _mmf.Dispose();
         throw;
     }
 }
コード例 #11
0
        public ConnectImpl()
        {
            _onDataUpdatedEvent = new EventWaitHandle(true, EventResetMode.ManualReset, OnDataUpdatedEventName);
            _onWriteLockMutex = new Mutex(false, OnWriteLockMutexName);

            using (GetLock())
            {
                try
                {
                    _memoryMappedFile = MemoryMappedFile.OpenExisting(MemoryMappedFileName);
                }
                catch (FileNotFoundException)
                {
                    _memoryMappedFile = MemoryMappedFile.CreateNew(MemoryMappedFileName, MemoryMappedFileSize);
                }

                _memoryMappedViewAccessor = _memoryMappedFile.CreateViewAccessor();
                _memoryMappedViewStream = _memoryMappedFile.CreateViewStream();
                _memoryMappedViewHandle = _memoryMappedViewStream.SafeMemoryMappedViewHandle.DangerousGetHandle();
            }
        }
コード例 #12
0
ファイル: ParityChange.cs プロジェクト: codeicon/disParity
 public ParityChange(Parity parity, Config config, UInt32 startBlock, UInt32 lengthInBlocks)
 {
     this.parity = parity;
       this.startBlock = startBlock;
       tempDir = config.TempDir;
       writingToMMF = true;
       UInt32 maxMMFBlocks = Parity.LengthInBlocks((long)config.MaxTempRAM * 1024 * 1024);
       UInt32 mmfBlocks = (lengthInBlocks < maxMMFBlocks) ? lengthInBlocks : maxMMFBlocks;
       try {
     mmf = MemoryMappedFile.CreateNew("disparity.tmp", (long)mmfBlocks * Parity.BLOCK_SIZE);
     mmfStream = mmf.CreateViewStream();
       }
       catch (Exception e) {
     LogFile.Log("Could not create memory mapped file: " + e.Message);
     // We'll use a temp file only
     mmf = null;
     mmfStream = null;
     writingToMMF = false;
       }
       tempFileStream = null;
       parityBlock = new ParityBlock(parity);
       block = startBlock;
 }
コード例 #13
0
        public DumpFileMemoryReader(string dumpFilePath)
        {
            bool dispose = true;
            FileStream fileStream = null;
            MemoryMappedFile memoryMappedFile = null;
            MemoryMappedViewStream stream = null;

            try
            {
                fileStream = new FileStream(dumpFilePath, FileMode.Open, FileAccess.Read);
                memoryMappedFile = MemoryMappedFile.CreateFromFile(fileStream, Guid.NewGuid().ToString(), fileStream.Length, MemoryMappedFileAccess.Read, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, false);
                stream = memoryMappedFile.CreateViewStream(0, fileStream.Length, MemoryMappedFileAccess.Read);

                stream.SafeMemoryMappedViewHandle.AcquirePointer(ref basePointer);
                IntPtr streamPointer = IntPtr.Zero;
                uint streamSize = 0;
                MINIDUMP_DIRECTORY directory = new MINIDUMP_DIRECTORY();

                if (!MiniDumpReadDumpStream((IntPtr)basePointer, MINIDUMP_STREAM_TYPE.Memory64ListStream, ref directory, ref streamPointer, ref streamSize))
                    throw new Exception("Unable to read mini dump stream");

                var data = (MINIDUMP_MEMORY64_LIST)Marshal.PtrToStructure(streamPointer, typeof(MINIDUMP_MEMORY64_LIST));
                ulong lastEnd = data.BaseRva;

                ranges = new MemoryLocation[data.NumberOfMemoryRanges];
                for (int i = 0; i < ranges.Length; i++)
                {
                    var descriptor = (MINIDUMP_MEMORY_DESCRIPTOR64)Marshal.PtrToStructure(streamPointer + sizeof(MINIDUMP_MEMORY64_LIST) + i * sizeof(MINIDUMP_MEMORY_DESCRIPTOR64), typeof(MINIDUMP_MEMORY_DESCRIPTOR64));
                    ranges[i] = new MemoryLocation()
                    {
                        MemoryStart = descriptor.StartOfMemoryRange,
                        MemoryEnd = descriptor.StartOfMemoryRange + descriptor.DataSize,
                        FilePosition = lastEnd,
                    };
                    lastEnd += descriptor.DataSize;
                }

                int newEnd = 0;
                for (int i = 1; i < ranges.Length; i++)
                    if (ranges[i].MemoryStart == ranges[newEnd].MemoryEnd)
                        ranges[newEnd].MemoryEnd = ranges[i].MemoryEnd;
                    else
                        ranges[++newEnd] = ranges[i];
                newEnd++;
                Array.Resize(ref ranges, newEnd);
                finder = new MemoryRegionFinder(ranges.Select(r => new MemoryRegion { BaseAddress = r.MemoryStart, MemoryEnd = r.MemoryEnd }).ToArray());
                dispose = false;
            }
            finally
            {
                if (dispose)
                {
                    stream.SafeMemoryMappedViewHandle.ReleasePointer();
                    if (stream != null)
                    {
                        stream.Dispose();
                    }

                    if (memoryMappedFile != null)
                    {
                        memoryMappedFile.Dispose();
                    }

                    if (fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }
                else
                {
                    this.fileStream = fileStream;
                    this.stream = stream;
                    this.memoryMappedFile = memoryMappedFile;
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// The copy next chunk async.
        /// </summary>
        /// <param name="memoryMappedFile">
        /// The memory mapped file.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="DownloadAcceleratorException">
        /// Thrown if the web server returns the wrong amount of data.
        /// </exception>
        private async Task<Status> CopyNextChunkAsync(MemoryMappedFile memoryMappedFile)
        {
            HttpWebRequest httpWebRequest = this.GetWebRequest();
            long chunkId;
            lock (this.stateLock)
            {
                if (this.chunkPosition == this.numberOfChunks)
                {
                    return Status.Complete;
                }

                chunkId = this.chunkPosition++;
            }

            long offset = chunkId * this.chunkSize;
            long length = Math.Min(this.chunkSize, this.Size - offset);
            httpWebRequest.AddRange(offset, offset + length - 1);

            using (WebResponse webResponse = await httpWebRequest.GetResponseAsync())
            {
                if (long.Parse(webResponse.Headers[HttpResponseHeader.ContentLength]) != length)
                {
                    throw new DownloadAcceleratorException("Server returned incorrect amount of data");
                }

                using (MemoryMappedViewStream memoryMappedViewStream = memoryMappedFile.CreateViewStream(offset, length))
                {
                    await this.CopyToWithProgressAsync(webResponse.GetResponseStream(), memoryMappedViewStream);
                }
            }

            return Status.Incomplete;
        }
コード例 #15
0
 private void Init()
 {
     mmf = MemoryMappedFile.OpenExisting(SHARE_MEMORY_NAME);
     mmfvs = mmf.CreateViewStream();
 }
コード例 #16
0
ファイル: MainForm.cs プロジェクト: tyranid/Sourcey-Jack
        private void MainForm_Load(object sender, EventArgs e)
        {
            _map = MemoryMappedFile.CreateNew("SJackConfig", 4096, MemoryMappedFileAccess.ReadWrite);
            using (Stream stm = _map.CreateViewStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stm))
                {
                }
            }

            UpdateMap();

            RefreshProcessList();
        }
コード例 #17
0
 /// <summary>
 /// 
 /// Read buffer from file and return it as a string
 /// </summary>
 /// <param name="mmf"></param>
 /// <param name="offset"></param>
 /// <param name="length"></param>
 /// <returns></returns>
 private string ReadFromFile(MemoryMappedFile mmf, long offset, long length)
 {
     using (var accessor = mmf.CreateViewStream(offset, length))
     {
         //TODO: There must be a better way to return the buffer.
         byte[] buffer = new byte[length + 1];
         int a = accessor.Read(buffer, 0, (int)length);
         return Encoding.ASCII.GetString(buffer, 0, a);
     }
 }
コード例 #18
0
        static void GetRequest(string url, long fileSize, MemoryMappedFile mmap, int fragNo, int count)
        {
            Interlocked.Increment(ref running);
            long length = fileSize / count;
            long offset = length * fragNo;

            Console.Out.WriteLine("Fragment {0} offset {1} size {2}", fragNo, offset, length);

            Stream file = mmap.CreateViewStream(offset, length);

            HttpWebRequest get = (HttpWebRequest)HttpWebRequest.Create(url);
            get.AddRange(offset, offset + length-1);

            get.BeginGetResponse((ar) =>
                {
                    try
                    {
                        WebResponse resp = get.EndGetResponse(ar);
                        Stream web = resp.GetResponseStream();

                        byte[] buffer = new byte[4096];
                        int position = 0;

                        AsyncCallback cbBuffer = null;
                        cbBuffer = (bar) =>
                             {
                                 try
                                 {
                                     int bytesRead = web.EndRead(bar);
                                     Console.Out.WriteLine("Fragment {0} read {1}", fragNo, bytesRead);
                                     if (0 < bytesRead)
                                     {
                                         // There are better ways to do this, eg. overlap reads and writes using 2 buffers
                                         file.BeginWrite(buffer, 0, bytesRead, (war) =>
                                         {
                                             try
                                             {
                                                 file.EndWrite(war);
                                                 position += bytesRead;
                                                 Console.Out.WriteLine("Fragment {0} write {1}", fragNo, bytesRead);
                                                 web.BeginRead(buffer, 0, buffer.Length, cbBuffer, null);
                                             }
                                             catch (Exception e)
                                             {
                                                 Console.Error.WriteLine(e);
                                                 CompleteOne();
                                             }
                                         }, null);
                                     }
                                     else
                                     {
                                         web.Dispose();
                                         file.Dispose();
                                         Console.Out.WriteLine("Fragment {0} done", fragNo);
                                         CompleteOne();
                                     }
                                 }
                                 catch (Exception e)
                                 {
                                     Console.Error.WriteLine(e);
                                     CompleteOne();
                                 }
                             };
                        // start reading
                        web.BeginRead(buffer, 0, buffer.Length, cbBuffer, null);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                        CompleteOne();
                    }
                }, null);
        }
コード例 #19
0
ファイル: MemoryManager.cs プロジェクト: Jehran/opencover
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId)
            {
                Namespace = @namespace;
                Key = key;

                ProfilerHasResults = new EventWaitHandle(false, EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId));

                ResultsHaveBeenReceived = new EventWaitHandle(false, EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId));

                _mmfResults = MemoryMappedFile.CreateNew(MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId), bufferSize);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
コード例 #20
0
 /// <summary>
 /// Load new stream from file starting at the given offset
 /// </summary>
 /// <param name="startOfStream"></param>
 /// <param name="accessor"></param>
 /// <param name="length"></param>
 /// <param name="mmf"></param>
 /// <param name="sizeOfFile"></param>
 /// <param name="offsetInFile"></param>
 private void LoadNewStream(ref long startOfStream, ref MemoryMappedViewStream accessor, int length, MemoryMappedFile mmf, long sizeOfFile, long offsetInFile)
 {
     long newStartOfStream = offsetInFile;
     long endPoint = newStartOfStream + length + chunckSize;
     long newLength = (endPoint > sizeOfFile) ? length : length + chunckSize;
     newLength = (newLength > chunckSize) ? chunckSize : newLength; //Do not load streams more than chunck
     accessor.Dispose();
     accessor = mmf.CreateViewStream(newStartOfStream, newLength);
     startOfStream = newStartOfStream;
 }
コード例 #21
0
ファイル: MemoryManager.cs プロジェクト: Jehran/opencover
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId)
            {
                Namespace = @namespace;
                Key = key;

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId), bufferSize);
                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                ProfilerRequestsInformation = new EventWaitHandle(false, EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId));

                InformationReadyForProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId));

                InformationReadByProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId));

                DataCommunication = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
コード例 #22
0
ファイル: Program.cs プロジェクト: palexster/ermesReloaded
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            client = new WlanClient();
            //Miofile = "C:\\" + DateTime.Now.ToLongDateString() + "-" +DateTime.Now.ToShortTimeString() + "_catture.txt";
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");

            // Initialize data structure
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = default_interval;
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");

            //initialize the mutex
            mut = new Mutex(false,"Global\\ServiceMutex");
            MutexSecurity mSec = mut.GetAccessControl();
            var rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                               MutexRights.Modify
                                | MutexRights.Synchronize
                                | MutexRights.TakeOwnership
                                | MutexRights.ReadPermissions,
                               AccessControlType.Allow);
            mSec.AddAccessRule(rule);
            mut.SetAccessControl(mSec);
            // Set the time interval

            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");
            // File Mapping creation
            try
            {
                mmf = MemoryMappedFile.CreateNew("Global\\Broadcast", MappedFileDimension, MemoryMappedFileAccess.ReadWrite);
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText("c:\\catture.txt", e.ToString());
            }
            var mmfSec = mmf.GetAccessControl();
            mmfSec.SetAccessRule(new AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null),MemoryMappedFileRights.FullControl | MemoryMappedFileRights.Read, AccessControlType.Allow));
            mmf.SetAccessControl(mmfSec);
            //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n");
            stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.ReadWrite);
            //System.IO.File.AppendAllText("c:\\catture.txt", "FINISCO PARTENZA\r\n");

            aTimer.Enabled = true;
        }
コード例 #23
0
ファイル: SolidKeyValueStorage.cs プロジェクト: vebin/BD2
 void EnsureCapacity(long required)
 {
     long newLength = capacity;
     while (newLength < required) {
         newLength += 0x100000;
     }
     if (newLength != capacity) {
         maData.Flush ();
         maData.Dispose ();
         mmfBlock.Dispose ();
         string blockFileName = path.CreatePath ("block").Path;
         FileStream fs = File.Open (blockFileName, FileMode.OpenOrCreate);
         if ((capacity = fs.Length) == 0)
             fs.SetLength (newLength);
         fs.Close ();
         mmfBlock = MemoryMappedFile.CreateFromFile (blockFileName, FileMode.Open);
         maData = mmfBlock.CreateViewStream ();
     }
 }
コード例 #24
0
ファイル: LageantCore.cs プロジェクト: bitbeans/lageant
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public bool CreateServer()
        {
            try
            {
                _memoryMappedFile = MemoryMappedFile.CreateOrOpen(_smKeyStoreName, _smKeyStoreSize);
                _reader = _memoryMappedFile.CreateViewAccessor(0, _smKeyStoreSize, MemoryMappedFileAccess.ReadWrite);
                _writer = _memoryMappedFile.CreateViewStream(0, _smKeyStoreSize, MemoryMappedFileAccess.ReadWrite);
                _keystoreLock = new Mutex(true, LageantLock, out _isLocked);
            }
            catch
            {
                return false;
            }

            return true;
        }
コード例 #25
0
        private void read_events_thread() {

            string prefix = use_global_ ? "Global\\" : "";
            try {
                memory_file_ = MemoryMappedFile.CreateNew(prefix + "DBWIN_BUFFER", 4096L);

                bool created = false;
                buffer_ready_ = new EventWaitHandle( false, EventResetMode.AutoReset, prefix + "DBWIN_BUFFER_READY", out created);
                if (!created) 
                    errors_.add("Can't create the DBWIN_BUFFER_READY event/" + use_global_);

                if (created) {
                    data_ready_ = new EventWaitHandle(false, EventResetMode.AutoReset, prefix + "DBWIN_DATA_READY", out created);
                    if (!created) 
                        errors_.add("Can't create the DBWIN_DATA_READY event/" + use_global_);
                }

                if (created) {
                    buffer_ready_.Set();
                    while (!disposed_) {
                        if (!data_ready_.WaitOne(1000))
                            continue;

                        using (var stream = memory_file_.CreateViewStream()) {
                            using (var reader = new BinaryReader(stream, Encoding.Default)) {
                                var process_id = (int)reader.ReadUInt32();
                                var raw = reader.ReadChars(4092);
                                var idx = Array.IndexOf(raw, '\0');
                                var msg = new string(raw, 0, idx);
                                find_process_id(process_id);
                                string process_name = pid_to_name_.ContainsKey(process_id) ? pid_to_name_[process_id] : "";
                                lock (this)
                                    events_.Add(new debug_event {
                                        unique_id = next_unique_id++, process_id = process_id, msg = msg, lo_process_name = process_name
                                    });
                            }
                        }
                
                        buffer_ready_.Set();
                    }
                }
            } catch (Exception e) {
                logger.Fatal("Can't read debug events " + e.Message);
                errors_.add("Error reading debug events " + e.Message);
            }

            if ( memory_file_ != null)
                memory_file_.Dispose();
            if ( data_ready_ != null)
                data_ready_.Dispose();
            if ( buffer_ready_ != null)
                buffer_ready_.Dispose();

        }
コード例 #26
0
ファイル: MemoryManager.cs プロジェクト: Sam13/opencover
            internal ManagedMemoryBlock(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));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    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));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId),
                    out createdNew,
                    open);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    open);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
コード例 #27
0
ファイル: MemoryManager.cs プロジェクト: Sam13/opencover
            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);
            }
コード例 #28
0
ファイル: SolidKeyValueStorage.cs プロジェクト: vebin/BD2
 void Initialize()
 {
     if (!Directory.Exists (path.Path))
         Directory.CreateDirectory (path.Path);
     string blockFileName = path.CreatePath (name).Path;
     Console.WriteLine ("Name: {0}", name);
     Console.WriteLine ("Block: {0}", blockFileName);
     bool blockExists = File.Exists (blockFileName);
     if (!blockExists) {
         FileStream fs;
         fs = File.Open (blockFileName, FileMode.OpenOrCreate);
         if ((capacity = fs.Length) == 0) {
             fs.SetLength (capacity = 0x100000);
             fs.WriteByte (0);
             fs.WriteByte (0);
             fs.WriteByte (1);//65536
             fs.WriteByte (0);
             fs.WriteByte (0);
             fs.WriteByte (0);
             fs.WriteByte (0);
             fs.WriteByte (0);
         }
         fs.Close ();
     }
     mmfBlock = MemoryMappedFile.CreateFromFile (blockFileName, FileMode.Open);
     maData = mmfBlock.CreateViewStream ();
     offset = (long)
         (((ulong)maData.ReadByte ()) |
     ((ulong)maData.ReadByte ()) << 8 |
     ((ulong)maData.ReadByte ()) << 16 |
     ((ulong)maData.ReadByte ()) << 24 |
     ((ulong)maData.ReadByte ()) << 32 |
     ((ulong)maData.ReadByte ()) << 40 |
     ((ulong)maData.ReadByte ()) << 48 |
     ((ulong)maData.ReadByte ()) << 56);
 }
コード例 #29
-1
        public SharedMemory(string name, IntPtr size)
        {
            mmf = MemoryMappedFile.OpenExisting(name + "_CONNECT_DATA");

            mmva = mmf.CreateViewAccessor();
            if (mmf.SafeMemoryMappedFileHandle.IsInvalid)
                throw new MySqlException("Cannot open file mapping " + name);
            mmvs = mmf.CreateViewStream(0L, size.ToInt64());
            mmva = mmf.CreateViewAccessor(0L, size.ToInt64());
        }