コード例 #1
0
ファイル: CircularBuffer.cs プロジェクト: ArcamEBM/LogStudio
 public void Stop()
 {
     m_Server.WaitForPipeDrain();
     m_Server.Close();
     m_Client.Close();
     m_Client.Dispose();
     m_Client = null;
     m_Server.Dispose();
     m_Server = null;
 }
コード例 #2
0
 public void Close()
 {
     if (!_disposed)
     {
         lock (this)
             if (!_disposed)
             {
                 _server.WaitForPipeDrain();
                 _server.Dispose();
                 _client.Dispose();
                 _disposed = true;
             }
     }
 }
コード例 #3
0
 private void SignalConsensusServerShutdown()
 {
     if (Interlocked.Exchange(ref _consensusServerStopped, 1) == 0)
     {
         _outPipe.Dispose();
     }
 }
コード例 #4
0
ファイル: ConsoleRedirector.cs プロジェクト: msavva/pigraphs
        private void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                lock (_sync)
                {
                    if (!_isDisposed)
                    {
                        _isDisposed = true;
                        _timer.Change(Timeout.Infinite, Timeout.Infinite);
                        _timer.Dispose();
                        flush(null);

                        try { SetStdHandle(STD_OUTPUT_HANDLE, _stdout); }
                        catch (Exception) { }
                        _outClient.Dispose();
                        _outServer.Dispose();

                        if (_forceConsoleRedirection)
                        {
                            ResetConsoleOutStream(); //Calls to Console.Write/WriteLine will now get redirected to the original stdout stream
                        }
                    }
                }
            }
        }
コード例 #5
0
ファイル: ROSInstallTask.cs プロジェクト: lhy26/ros_cygwin
 public void Dispose()
 {
     _OutPipe.Dispose();
     _TarStream.Dispose();
     _LogStream?.Close();
     _LogStream = null;
 }
コード例 #6
0
            // ReSharper disable InconsistentNaming
            // ReSharper disable UnusedParameter.Local
            // ReSharper disable EmptyGeneralCatchClause
            private void Dispose(bool disposing)
            {
                if (!_isDisposed)
                {
                    lock (_sync)
                    {
                        if (!_isDisposed)
                        {
                            _isDisposed = true;
                            _timer.Change(Timeout.Infinite, Timeout.Infinite);
                            _timer.Dispose();
                            flush(null);

                            try { SetStdHandle(STD_OUTPUT_HANDLE, _stdout); }
                            catch (Exception) { }
                            _outClient.Dispose();
                            _outServer.Dispose();

                            try { SetStdHandle(STD_ERROR_HANDLE, _stderr); }
                            catch (Exception) { }
                            _errClient.Dispose();
                            _errServer.Dispose();
                        }
                    }
                }
            }
コード例 #7
0
        public async Task AnonymousPipeViaFileStream_AllDataCopied(int writeSize, int numWrites)
        {
            long totalLength  = writeSize * numWrites;
            var  expectedData = new byte[totalLength];

            new Random(42).NextBytes(expectedData);

            var results = new MemoryStream();

            using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                Task serverTask = Task.Run(async() =>
                {
                    for (int i = 0; i < numWrites; i++)
                    {
                        await server.WriteAsync(expectedData, i * writeSize, writeSize);
                    }
                });

                using (var client = new FileStream(new SafeFileHandle(server.ClientSafePipeHandle.DangerousGetHandle(), false), FileAccess.Read, bufferSize: 3))
                {
                    Task copyTask = client.CopyToAsync(results, writeSize);
                    await await Task.WhenAny(serverTask, copyTask);

                    server.Dispose();
                    await copyTask;
                }
            }

            byte[] actualData = results.ToArray();
            Assert.Equal(expectedData.Length, actualData.Length);
            Assert.Equal <byte>(expectedData, actualData);
        }
コード例 #8
0
        public void ServerClosesPipe_ClientReceivesEof()
        {
            using (var pipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                using (var remote = RemoteExecutor.Invoke(new Action <string>(ChildFunc), pipe.GetClientHandleAsString()))
                {
                    pipe.DisposeLocalCopyOfClientHandle();
                    pipe.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);

                    pipe.Dispose();

                    Assert.True(remote.Process.WaitForExit(30_000));
                }

            void ChildFunc(string clientHandle)
            {
                using (var pipe = new AnonymousPipeClientStream(PipeDirection.In, clientHandle))
                {
                    for (int i = 1; i <= 5; i++)
                    {
                        Assert.Equal(i, pipe.ReadByte());
                    }
                    Assert.Equal(-1, pipe.ReadByte());
                }
            }
        }
コード例 #9
0
        public void Dispose()
        {
            _streamIn.Dispose();
            _streamOut.Dispose();
            _pipeIn.Dispose();
            _pipeOut.Dispose();

            _coreProcess.WaitForExit(EXIT_MAXWAIT);
        }
コード例 #10
0
 /// <summary>
 /// Waits for the termination of the internal thread and closes the pipe.
 /// Even if this can be called immediately, you should first call <see cref="WaitEnd(bool)"/>
 /// before calling Dispose.
 /// </summary>
 public void Dispose()
 {
     if (_endFlag == LogReceiverEndStatus.None)
     {
         _thread.Join();
     }
     _reader.Dispose();
     _server.Dispose();
 }
コード例 #11
0
ファイル: PipeServer.cs プロジェクト: S031/IpcChannel
 public void Dispose()
 {
     Logger.LogInfo($"Server {PipeReadHandle}-{PipeWriteHandle}  disposing");
     _workProcess?.Close();
     _ewh.Dispose();
     _pipeRead?.Dispose();
     _pipeWrite.Dispose();
     Logger.Flush();
 }
コード例 #12
0
        public static void ServerWriteOnlyDisconnectedPipeThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
                using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
                {
                    server.Dispose();

                    OtherSidePipeDisconnectVerifyRead(client);
                }
        }
コード例 #13
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _inServer?.Dispose();
         _outServer?.Dispose();
         _inClient?.Dispose();
         _outClient?.Dispose();
     }
 }
コード例 #14
0
        /// <summary>
        /// Erzeugt eine neue Implementierung.
        /// </summary>
        internal OutOfProcessCardServer()
        {
            // Streams to use
            AnonymousPipeServerStream writer = null, reader = null;

            try
            {
                // Create streams
                writer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
                reader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);

                // Create start information
                ProcessStartInfo info = new ProcessStartInfo();

                // Configure
                info.Arguments       = string.Format("\"{0}\" \"{1}\"", writer.GetClientHandleAsString().Replace("\"", "\"\""), reader.GetClientHandleAsString().Replace("\"", "\"\""));
                info.FileName        = Path.Combine(RunTimeLoader.ServerDirectory.FullName, "JMS.DVB.CardServer.exe");
                info.UseShellExecute = false;
                info.LoadUserProfile = true;

                // With cleanup
                try
                {
                    // Create the process
                    Process.Start(info);
                }
                finally
                {
                    // Destroy temporary data
                    writer.DisposeLocalCopyOfClientHandle();
                    reader.DisposeLocalCopyOfClientHandle();
                }

                // Remember
                m_RequestStream  = writer;
                m_ResponseStream = reader;

                // Avoid cleanup
                writer = null;
                reader = null;
            }
            finally
            {
                // Cleanup all
                if (null != writer)
                {
                    writer.Dispose();
                }
                if (null != reader)
                {
                    reader.Dispose();
                }
            }
        }
コード例 #15
0
 /// <summary>
 /// Cleans up resources.
 /// </summary>
 public void Dispose()
 {
     if (childProcess != null)
     {
         childProcess.Dispose();
         childProcess = null;
         inPipe.Dispose();
         inPipe = null;
         outPipe.Dispose();
         outPipe = null;
     }
 }
コード例 #16
0
 public void KillTestRunner()
 {
     try
     {
         _runnerProcess.Kill();
         runnerStreamIn.Dispose();
         runnerStreamOut.Dispose();
         _runnerPipeIn.Dispose();
         _runnerPipeOut.Dispose();
     }
     catch { }
 }
コード例 #17
0
 override public void Dispose()
 {
     base.Dispose();
     PipeToClient.Dispose();
     PipeFromClient.Dispose();
     try {
         Client.Kill();
     } catch (Exception) {
         // don't care
     }
     Client.Close();
 }
コード例 #18
0
ファイル: Aqueduct.cs プロジェクト: mindis/memcache-driver
 public void Dispose()
 {
     if (!_disposed)
     {
         lock (this)
             if (!_disposed)
             {
                 _server.Dispose();
                 _client.Dispose();
                 _disposed = true;
             }
     }
 }
コード例 #19
0
        public void Dispose()
        {
            CommandExchanger.SendData(_streamCmd, CommandExchanger.Commands.STOP);

            _streamIn.Dispose();
            _streamOut.Dispose();
            _streamCmd.Dispose();
            _pipeIn.Dispose();
            _pipeOut.Dispose();
            _pipeCmd.Dispose();

            _coreProcess.WaitForExit(EXIT_MAXWAIT);
        }
コード例 #20
0
        /// <summary>
        /// Beendet die Nutzung dieser Instanz endgültig.
        /// </summary>
        protected override void OnDispose()
        {
            // Forward to base
            base.OnDispose();

            // Check streams
            if (null != m_ResponseStream)
            {
                try
                {
                    // Forward
                    m_ResponseStream.Dispose();
                }
                catch
                {
                    // Ignore any error
                }
                finally
                {
                    // Forget
                    m_ResponseStream = null;
                }
            }
            if (null != m_RequestStream)
            {
                try
                {
                    // Forward
                    m_RequestStream.Dispose();
                }
                catch
                {
                    // Ignore any error
                }
                finally
                {
                    // Forget
                    m_RequestStream = null;
                }
            }

            // Wait for thread to finish
            if (null != m_Worker)
            {
                // Synchronize
                m_Worker.Join();

                // Forget
                m_Worker = null;
            }
        }
コード例 #21
0
 private static void Exit(object sender, EventArgs e)
 {
     sw.WriteLine("TERMINATED");
     sw?.Close();
     serverStream?.Dispose();
     chooser.KinectChanged -= KinectUpdate;
     chooser?.Stop();
     beatSaber?.Dispose();
     if (sensor != null)
     {
         sensor.SkeletonFrameReady -= SkeletonFrameReady;
         sensor.Stop();
     }
 }
コード例 #22
0
        public void StartSessionMuter(uint sessId)
        {
            // test if we already have the session data
            if (_MuterSessions.ContainsKey(sessId))
            {
                var pipes = _MuterSessions[sessId];
                // ensure the pipe is working
                try
                {
                    pipes.Item1.WriteByte((byte)SessionMuter.Commands.PING);
                    pipes.Item2.ReadByte();
                    // do nothing if success
                    return;
                }
                catch (Exception)
                {
                    // very likely broken pipe. erase this pipe and create new child.
                    CloseSessionMuter(sessId);
                }
            }

            // create new anon pipes
            AnonymousPipeServerStream pipeServerOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            AnonymousPipeServerStream pipeServerIn  = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            // open process
            bool success = false;

            try
            {
                success = SpawnInSession.StartProcessInSession(Assembly.GetExecutingAssembly().Location, sessId,
                                                               $"ProcessName.exe startsessionmuter {Process.GetCurrentProcess().Id} {pipeServerOut.GetClientHandleAsString()} {pipeServerIn.GetClientHandleAsString()}");
            }
            catch (Exception) { success = false; }

            pipeServerIn.DisposeLocalCopyOfClientHandle();
            pipeServerOut.DisposeLocalCopyOfClientHandle();

            if (success)
            {
                _MuterSessions[sessId] = new Tuple <PipeStream, PipeStream>(pipeServerOut, pipeServerIn);
            }
            else
            {
                pipeServerOut.Dispose();
                pipeServerIn.Dispose();
            }
        }
コード例 #23
0
 public void Dispose()
 {
     isDisposed = true;
     Core.LoggingService.Debug("Telling worker process to exit");
     hostToWorkerPipe.Dispose();             // send "end-of-stream" to worker
     if (Thread.CurrentThread != readerThread)
     {
         // don't deadlock when disposing from within ReaderThread event
         Core.LoggingService.Debug("Waiting for thread-join");
         if (!readerThread.Join(3000))
         {
             Core.LoggingService.Debug("Thread-join failed. Killing worker process.");
             Kill();
             Core.LoggingService.Debug("Waiting for thread-join");
             readerThread.Join();
         }
         Core.LoggingService.Debug("Joined!");
     }
     workerToHostPipe.Dispose();
     process.Dispose();
 }
コード例 #24
0
        private bool WaitForConnectionFromProcess(AnonymousPipeServerStream clientToServerStream,
                                                  AnonymousPipeServerStream serverToClientStream,
                                                  int nodeProcessId, long hostHandshake, long clientHandshake)
        {
            try
            {
                CommunicationsUtilities.Trace("Attempting to handshake with PID {0}", nodeProcessId);

                CommunicationsUtilities.Trace("Writing handshake to pipe");
                serverToClientStream.WriteLongForHandshake(hostHandshake);

                CommunicationsUtilities.Trace("Reading handshake from pipe");
                long handshake = clientToServerStream.ReadLongForHandshake();

                if (handshake != clientHandshake)
                {
                    CommunicationsUtilities.Trace("Handshake failed. Received {0} from client not {1}. Probably the client is a different MSBuild build.", handshake, clientHandshake);
                    throw new InvalidOperationException();
                }

                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected got connection from PID {0}...!", nodeProcessId);
                return(true);
            }
            catch (Exception ex)
            {
                if (ExceptionHandling.IsCriticalException(ex))
                {
                    throw;
                }

                CommunicationsUtilities.Trace("Failed to get connection from PID {0}. {1}", nodeProcessId, ex.ToString());

                clientToServerStream.Dispose();
                serverToClientStream.Dispose();

                return(false);
            }
        }
コード例 #25
0
        public void StartListeningOn(params string[] prefixes)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            // for example "http://contoso.com:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }
            listener.Start();
            while (true)
            {
                Console.WriteLine("Listening...");
                // Note: The GetContext method blocks while waiting for a request.
                var context           = listener.GetContext();
                var request           = context.Request;
                var response          = context.Response;
                var serializedRequest = new System.
                                        pipeServer.Write(context.Request)
            }
            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
            pipeServer.Dispose();
            listener.Stop();
        }
コード例 #26
0
ファイル: anonym_pipe.cs プロジェクト: inwenis/stream_funs
    public static void Main()
    {
        AnonymousPipeServerStream pipeServer =
            new AnonymousPipeServerStream(PipeDirection.Out,
                                          HandleInheritability.Inheritable);
        var clientPipeHandle = pipeServer.GetClientHandleAsString();

        Console.WriteLine(clientPipeHandle);

        Process pipeClient = new Process();

        pipeClient.StartInfo.FileName        = "client.exe";
        pipeClient.StartInfo.Arguments       = clientPipeHandle;
        pipeClient.StartInfo.UseShellExecute = false;
        pipeClient.Start();

        pipeServer.DisposeLocalCopyOfClientHandle();
        pipeServer.WriteByte(45);
        pipeServer.Flush();
        Console.WriteLine("Press any key to quit");
        Console.ReadKey();
        pipeServer.Dispose();
    }
コード例 #27
0
        /// <summary>
        /// Releases all resources used by the Ghostscript.NET.GhostscriptPipedOutput instance.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_pipe != null)
                    {
                        // _pipe.DisposeLocalCopyOfClientHandle();

                        // for some reason at this point the handle is invalid for real.
                        // DisposeLocalCopyOfClientHandle should be called instead, but it
                        // throws an exception saying that the handle is invalid pointing to
                        // CloseHandle method in the dissasembled code.
                        // this is a workaround, if we don't set the handle as invalid, when
                        // garbage collector tries to dispose this handle, exception is thrown
                        _pipe.ClientSafePipeHandle.SetHandleAsInvalid();

                        _pipe.Dispose(); _pipe = null;
                    }

                    if (_thread != null)
                    {
                        // check if the thread is still running
                        if (_thread.ThreadState == ThreadState.Running)
                        {
                            // abort the thread
                            _thread.Abort();
                        }

                        _thread = null;
                    }
                }

                _disposed = true;
            }
        }
コード例 #28
0
        public static void ServerWriteOnlyDisconnectedPipeThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
            {
                server.Dispose();

                OtherSidePipeDisconnectVerifyRead(client);
            }
        }
コード例 #29
0
 public void Dispose()
 {
     pipeServer?.Dispose();
     pipeClient?.Dispose();
 }
コード例 #30
0
 public void Dispose()
 {
     _out.Dispose();
     _in.Dispose();
 }
コード例 #31
0
        public R <(string, Thread, TimeSpan?), LocalStr> StreamSongToPipeHandle(string spotifyTrackUri)
        {
            var trackId = SpotifyApi.UriToTrackId(spotifyTrackUri);

            if (!trackId.Ok)
            {
                return(new LocalStr("Cannot stream this URI from spotify."));
            }

            if (state == State.NotSetUp)
            {
                return(new LocalStr("Spotify API access was not set up correctly. Cannot play from spotify."));
            }

            if (state != State.Idle)
            {
                throw new InvalidOperationException(
                          $"Tried to stream spotify song while the system was not idle (current state: {state})."
                          );
            }

            // Launch Librespot.
            state = State.LaunchingLibrespot;
            Log.Debug("Launching Librespot...");
            var processOption = LaunchLibrespot();

            if (!processOption.Ok)
            {
                return(processOption.Error);
            }

            void Fail(string msg)
            {
                Log.Debug("Failed to start song on spotify: " + msg);
            }

            TimeSpan duration = default;

            for (var i = 0; i < SongStartRetries; i++)
            {
                Log.Debug($"Starting to play song on spotify, try {i}...");

                // Start song.
                var playResult = api.Request(
                    () => api.Client.Player.ResumePlayback(new PlayerResumePlaybackRequest {
                    DeviceId = deviceId,
                    Uris     = new List <string> {
                        spotifyTrackUri
                    }
                })
                    );
                if (!playResult.Ok)
                {
                    Fail(playResult.Error.ToString());
                    continue;
                }

                // Check if the song actually started playing.
                for (var j = 0; j < 2; j++)
                {
                    if (j == 1)
                    {
                        // Wait before the second check.
                        Thread.Sleep(SongStartRecheckAfter);
                    }

                    var checkResult = api.Request(() => api.Client.Player.GetCurrentPlayback());
                    if (!checkResult.Ok)
                    {
                        Fail(checkResult.Error.ToString());
                        continue;
                    }

                    var currentlyPlaying = checkResult.Value;

                    if (currentlyPlaying.CurrentlyPlayingType != "track")
                    {
                        Fail("No track is currently playing.");
                        continue;
                    }

                    var track = (FullTrack)currentlyPlaying.Item;

                    if (
                        currentlyPlaying.IsPlaying &&
                        currentlyPlaying.Device.Id == deviceId &&
                        track.Id == trackId.Value
                        )
                    {
                        duration = TimeSpan.FromMilliseconds(track.DurationMs);
                        state    = State.StreamRunning;
                        break;
                    }

                    Fail(
                        $"Song not playing yet on spotify." +
                        $" IsPlaying: {currentlyPlaying.IsPlaying}," +
                        $" DeviceId: {currentlyPlaying.Device.Id} (should be {deviceId})," +
                        $" TrackId: {track.Id} (should be {trackId.Value})."
                        );
                }

                if (state == State.StreamRunning)
                {
                    Log.Trace("Song is playing on spotify now.");
                    break;
                }
            }

            // Start audio streaming to ffmpeg.
            Log.Debug("Starting stream...");
            var pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            var handle     = "pipe:" + pipeServer.GetClientHandleAsString();

            var totalBytesSent = 0;

            void ExitLibrespot(string message, bool stats = true)
            {
                pipeServer.Dispose();

                if (!process.HasExitedSafe())
                {
                    process.Kill();
                }
                process.Close();

                state = State.Idle;

                var msg = message;

                if (stats)
                {
                    msg += $" Sent {byteSizeFormatter.Format(totalBytesSent)} bytes in total.";
                }
                Log.Debug(msg);
            }

            if (state != State.StreamRunning)
            {
                var msg = $"Song did not start playing after {SongStartRetries} retries.";
                ExitLibrespot(msg, false);
                return(new LocalStr(msg));
            }

            var byteReaderThread = new Thread(() => {
                var buffer = new byte[BytesPerChunk];
                while (true)
                {
                    int bytesRead;
                    try {
                        bytesRead = process.StandardOutput.BaseStream.Read(buffer, 0, BytesPerChunk);
                    } catch (IOException e) {
                        ExitLibrespot($"Reading from Librespot failed: {e}.");
                        return;
                    }

                    if (bytesRead == 0)
                    {
                        // Librespot exited, no more data coming.
                        ExitLibrespot("All spotify streaming data sent to ffmpeg.");
                        return;
                    }

                    try {
                        pipeServer.Write(buffer, 0, bytesRead);
                    } catch (IOException) {
                        ExitLibrespot("Ffmpeg went away before all spotify stream data was sent.");
                        return;
                    }

                    if (totalBytesSent == 0)
                    {
                        // Necessary to dispose the handle after ffmpeg connected to receive notice when ffmpeg exits.
                        pipeServer.DisposeLocalCopyOfClientHandle();
                    }

                    totalBytesSent += bytesRead;
                }
            })
            {
                IsBackground = true
            };

            return(handle, byteReaderThread, duration);
        }