Exemplo n.º 1
0
        static void Main()
        {
            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            {
                Process child = new Process();
                child.StartInfo.FileName = @"d:\mysrc\csharp\Solution1\PipeClient\bin\Debug\PipeClient.exe";
                child.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                child.StartInfo.UseShellExecute = false;

                child.Start();
                pipeServer.DisposeLocalCopyOfClientHandle();

                using (StreamReader pipeReader = new StreamReader(pipeServer))
                {
                    string line = pipeReader.ReadLine();
                    while (line != "QUIT")
                    {
                        Console.Out.WriteLine(line);
                        line = pipeReader.ReadLine();
                    }
                }

                child.WaitForExit();
                child.Close();
            }
        }
Exemplo n.º 2
0
        public ChiefWorkerProcess(
            ILog log,
            ServerSettingsBase workerSettings)
        {
            _log = log;
            _settings = workerSettings;
            Name = _settings.SourceSettings.Name;

            _logReceiverPipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            _logReceiverThread = new Thread(LogReceiverThreadJob)
                {
                    IsBackground = true
                };

            _process = new Process
                {
                    EnableRaisingEvents = true,
                    StartInfo =
                        {
                            FileName = Path.Combine(
                                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                "IpCamEmu Console.exe"),
                            UseShellExecute = false,
                            ErrorDialog = false,
                            CreateNoWindow = true
                        }
                };
            _process.Exited += delegate { _process = null; };

            _launchProcessThread = new Thread(LaunchWorkerThreadJob)
                {
                    IsBackground = true
                };
        }
        // ReSharper disable UseObjectOrCollectionInitializer
        private ConsoleRedirector(ILogListener logListener)
        {
            bool ret;
            AnonymousPipeClientStream client;

            _logListener = logListener;
            _stdout = GetStdHandle(STD_OUTPUT_HANDLE);
            _stderr = GetStdHandle(STD_ERROR_HANDLE);
            _sync = new Mutex();
            _buffer = new char[BUFFER_SIZE];

            _outServer = new AnonymousPipeServerStream(PipeDirection.Out);
            client = new AnonymousPipeClientStream(PipeDirection.In, _outServer.ClientSafePipeHandle);
            //client.ReadTimeout = 0;
            Debug.Assert(_outServer.IsConnected);
            _outClient = new StreamReader(client, Encoding.Default);
            ret = SetStdHandle(STD_OUTPUT_HANDLE, _outServer.SafePipeHandle.DangerousGetHandle());
            Debug.Assert(ret);

            _errServer = new AnonymousPipeServerStream(PipeDirection.Out);
            client = new AnonymousPipeClientStream(PipeDirection.In, _errServer.ClientSafePipeHandle);
            //client.ReadTimeout = 0;
            Debug.Assert(_errServer.IsConnected);
            _errClient = new StreamReader(client, Encoding.Default);
            ret = SetStdHandle(STD_ERROR_HANDLE, _errServer.SafePipeHandle.DangerousGetHandle());
            Debug.Assert(ret);

            Thread outThread = new Thread(doRead);
            Thread errThread = new Thread(doRead);
            outThread.Name = "stdout logger";
            errThread.Name = "stderr logger";
            outThread.Start(_outClient);
            errThread.Start(_errClient);
            _timer = new Timer(flush, null, PERIOD, PERIOD);
        }
Exemplo n.º 4
0
    public static void ClientSendsByteServerReceives()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Assert.True(server.IsConnected);
            server.ReadMode = PipeTransmissionMode.Byte;

            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.Out, server.ClientSafePipeHandle))
            {
                Assert.True(server.IsConnected);
                Assert.True(client.IsConnected);
                client.ReadMode = PipeTransmissionMode.Byte;

                byte[] sent = new byte[] { 123 };
                byte[] received = new byte[] { 0 };
                client.Write(sent, 0, 1);

                server.DisposeLocalCopyOfClientHandle();

                Assert.Equal(1, server.Read(received, 0, 1));
                Assert.Equal(sent[0], received[0]);
            }
            // not sure why the following isn't thrown because pipe is broken
            //Assert.Throws<System.IO.IOException>(() => server.ReadByte());
        }
    }
        private void Reader()
        {
            try
            {
                WriteLine("anonymous pipe reader");
                var pipeReader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None);
                using (var reader = new StreamReader(pipeReader))
                {
                    _pipeHandle = pipeReader.GetClientHandleAsString();
                    WriteLine($"pipe handle: {_pipeHandle}");
                    _pipeHandleSet.Set();
                    bool end = false;
                    while (!end)
                    {
                        string line = reader.ReadLine();
                        WriteLine(line);
                        if (line == "end") end = true;
                    }
                    WriteLine("finished reading");

                }
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
Exemplo n.º 6
0
        public async Task AnonymousPipeWriteViaFileStream(bool asyncWrites)
        {
            using (var server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Task serverTask = Task.Run(() =>
                {
                    for (int i = 0; i < 6; i++)
                        Assert.Equal(i, server.ReadByte());
                });

                using (var client = new FileStream(new SafeFileHandle(server.ClientSafePipeHandle.DangerousGetHandle(), false), FileAccess.Write, bufferSize: 3))
                {
                    var data = new[] { new byte[] { 0, 1 }, new byte[] { 2, 3 }, new byte[] { 4, 5 } };
                    foreach (byte[] arr in data)
                    {
                        if (asyncWrites)
                            await client.WriteAsync(arr, 0, arr.Length);
                        else
                            client.Write(arr, 0, arr.Length);
                    }
                }

                await serverTask;
            }
        }
Exemplo n.º 7
0
    public void ForNonSeekable(string input, params string[] lines)
    {
        using (var s = new AnonymousPipeServerStream())
        using (var c = new AnonymousPipeClientStream(s.GetClientHandleAsString()))
        {
            var bytes = Encoding.ASCII.GetBytes(input);
            s.Write(bytes, 0, bytes.Length);
            s.Close();

            var skipLF = false;
            foreach (var line in lines)
            {
                Assert.Equal(line, c.ReadProtocolLineWithEnd(skipLF));
                skipLF = (line.Last() == '\r');
            }
        }

        using (var s = new AnonymousPipeServerStream())
        using (var c = new AnonymousPipeClientStream(s.GetClientHandleAsString()))
        {
            var bytes = Encoding.ASCII.GetBytes(input);
            s.Write(bytes, 0, bytes.Length);
            s.Close();

            var skipLF = false;
            foreach (var line in lines)
            {
                Assert.Equal(line.TrimEnd(LineEnds), c.ReadProtocolLine(skipLF));
                skipLF = (line.Last() == '\r');
            }
        }
    }
Exemplo n.º 8
0
        static void Main()
        {
            Process pipeClient = new Process();

            pipeClient.StartInfo.FileName = "AnonymousPipeClient.exe";

            using (AnonymousPipeServerStream pipeServer =
                new AnonymousPipeServerStream(PipeDirection.Out,
                HandleInheritability.Inheritable))
            {
                // Show that anonymous pipes do not support Message mode.
                try
                {
                    Console.WriteLine("[SERVER] Setting ReadMode to \"Message\".");
                    pipeServer.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[SERVER] Exception:\n    {0}", e.Message);
                }

                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                    pipeServer.TransmissionMode);

                // Pass the client process a handle to the server.
                pipeClient.StartInfo.Arguments =
                    pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        // Send the console input to the client process.
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
Exemplo n.º 9
0
        public Relay(Options options)
        {
            log.Info("creating relay host");

            log.Debug("create interprocess input pipe");
            pipeIn = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            pipeReader = new StreamReader(pipeIn);

            log.Debug("create interprocess output pipe");
            pipeOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            pipeWriter = new StreamWriter(pipeOut);

            log.Debug("create processor host");
            processor = new Process();
            processor.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            log.DebugFormat("StartInfo.FileName={0}", processor.StartInfo.FileName);
            processor.StartInfo.Arguments = String.Format("--pipe-in={0} --pipe-out={1} process", pipeOut.GetClientHandleAsString(), pipeIn.GetClientHandleAsString());
            log.DebugFormat("StartInfo.Arguments={0}", processor.StartInfo.Arguments);
            processor.StartInfo.UseShellExecute = false;

            log.Debug("start processor host");
            try
            {
                processor.Start();
            }
            catch (Exception ex)
            {
                log.Fatal("Exception while starting processor host.", ex);
                throw ex;
            }
            log.DebugFormat("processor host process id : {0}", processor.Id);

            log.Debug("join processes into a job so processor host dies together with relay host");
            job = new Job();
            job.AddProcess(Process.GetCurrentProcess().Id);
            job.AddProcess(processor.Id);

            log.Debug("create native messaging ports");
            portA = new Port();
            portB = new Port(pipeIn, pipeOut);
            portsExceptions = new List<Exception>();

            log.Debug("create stop event");
            stop = new ManualResetEvent(false);

            log.Debug("synchronize processes");
            string sync = "SYNC";
            pipeWriter.WriteLine(sync);
            pipeWriter.Flush();
            log.DebugFormat("sent {0}", sync);
            pipeOut.WaitForPipeDrain();
            sync = pipeReader.ReadLine();
            log.DebugFormat("received {0}", sync);

            log.Info("created relay host");
        }
Exemplo n.º 10
0
        public static void ServerWriteBufferNullThrows()
        {
            // force different constructor path
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None))
            {
                Assert.Throws<ArgumentNullException>(() => server.Write(null, 0, 1));

                Assert.ThrowsAsync<ArgumentNullException>(() => server.WriteAsync(null, 0, 1));
            }
        }
Exemplo n.º 11
0
        public static void ServerReadModeThrows()
        {
            // force different constructor path
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream())
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);

                Assert.Throws<NotSupportedException>(() => server.ReadMode = PipeTransmissionMode.Message);
            }
        }
Exemplo n.º 12
0
 public void StartServer(StartProcessDelegate startProcess)
 {
     _outServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
     _inServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
     _readStream = new StreamString(_inServer);
     _writeStream = new StreamString(_outServer);
     startProcess(_outServer.GetClientHandleAsString(), _inServer.GetClientHandleAsString());
     _outServer.DisposeLocalCopyOfClientHandle();
     _inServer.DisposeLocalCopyOfClientHandle();
 }
Exemplo n.º 13
0
        public static void ServerBadPipeDirectionThrows()
        {
            Assert.Throws<NotSupportedException>(() => new AnonymousPipeServerStream(PipeDirection.InOut));
            Assert.Throws<NotSupportedException>(() => new AnonymousPipeServerStream(PipeDirection.InOut, HandleInheritability.None));
            Assert.Throws<NotSupportedException>(() => new AnonymousPipeServerStream(PipeDirection.InOut, HandleInheritability.None, 500));

            using (AnonymousPipeServerStream dummyserver = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                Assert.Throws<NotSupportedException>(() => new AnonymousPipeServerStream(PipeDirection.InOut, dummyserver.SafePipeHandle, null));
            }
        }
Exemplo n.º 14
0
 public void CanSeekReturnsFalseForPipe()
 {
     using (var pipeStream = new AnonymousPipeServerStream())
     using (var clientHandle = pipeStream.ClientSafePipeHandle)
     {
         SafeFileHandle handle = new SafeFileHandle((IntPtr)int.Parse(pipeStream.GetClientHandleAsString()), false);
         using (FileStream fs = new FileStream(handle, FileAccess.Write, 1, false))
         {
             Assert.False(fs.CanSeek);
         }
     }
 }
Exemplo n.º 15
0
        public static void ServerBadPipeHandleThrows()
        {
            using (AnonymousPipeServerStream dummyserver = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                Assert.Throws<ArgumentNullException>(() =>new AnonymousPipeServerStream(PipeDirection.Out, null, dummyserver.ClientSafePipeHandle));

                Assert.Throws<ArgumentNullException>(() =>new AnonymousPipeServerStream(PipeDirection.Out, dummyserver.SafePipeHandle, null));

                SafePipeHandle pipeHandle = new SafePipeHandle(new IntPtr(-1), true);
                Assert.Throws<ArgumentException>(() =>new AnonymousPipeServerStream(PipeDirection.Out, pipeHandle, dummyserver.ClientSafePipeHandle));

                Assert.Throws<ArgumentException>(() =>new AnonymousPipeServerStream(PipeDirection.Out, dummyserver.SafePipeHandle, pipeHandle));
            }
        }
Exemplo n.º 16
0
        public Relay(Program.Options options)
        {
            log.Debug("creating relay host");

            log.Debug("create interprocess input pipe");
            pipeIn = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);

            log.Debug("create interprocess output pipe");
            pipeOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);

            log.Debug("create sync event");
            sync = new ManualResetEvent(false);

            log.Debug("create processor host");
            processor = new Process();
            processor.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            log.DebugFormat("StartInfo.FileName={0}", processor.StartInfo.FileName);
            processor.StartInfo.Arguments = String.Format("--pipe-in={0} --pipe-out={1} process", pipeOut.GetClientHandleAsString(), pipeIn.GetClientHandleAsString());
            log.DebugFormat("StartInfo.Arguments={0}", processor.StartInfo.Arguments);
            processor.StartInfo.UseShellExecute = false;
            //// processor.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  ???? do we really need this ????

            log.Debug("start processor host");
            try
            {
                processor.Start();
            }
            catch (Exception ex)
            {
                log.Fatal("Exception while starting processor host.", ex);
                throw ex;
            }
            log.DebugFormat("processor host process id : {0}", processor.Id);

            log.Debug("join processes into a job so processor host dies together with relay host");
            job = new Job();
            job.AddProcess(Process.GetCurrentProcess().Id);
            job.AddProcess(processor.Id);

            log.Debug("create native messaging ports");
            portA = new Port();
            portB = new Port(pipeIn, pipeOut);
            portsExceptions = new List<Exception>();

            log.Debug("create stop event");
            stop = new ManualResetEvent(false);

            log.Debug("relay host created");
        }
        private static void AnonymousReader()
        {
            using (var reader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            {
                WriteLine("using anonymous pipe");
                string pipeHandle = reader.GetClientHandleAsString();
                WriteLine($"pipe handle: {pipeHandle}");

                byte[] buffer = new byte[256];
                int nRead = reader.Read(buffer, 0, 256);
                
                string line = Encoding.UTF8.GetString(buffer, 0, 256);
                WriteLine(line);
            }
        }
Exemplo n.º 18
0
        public static void Main()
        {
            Process pipeClient = new Process();
            pipeClient.StartInfo.FileName = "PipeClient.exe";

            using (var pipeServer = new AnonymousPipeServerStream(PipeDirection.Out,
                HandleInheritability.Inheritable))
            {
                try
                {
                    Console.Write("[SERVER] Setting ReadMode to \"Message\".");
                    pipeServer.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[SERVER] Exception:\n  {0}", e.Message);
                }

                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", pipeServer.TransmissionMode);

                pipeClient.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();
                try
                {
                    using (var sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine("SYNC"); // Send a 'sync message' and wait for client to receive it.
                        pipeServer.WaitForPipeDrain();
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                catch (IOException e) // if the pipe is broken or disconnected.
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
Exemplo n.º 19
0
		// AnonymousPipeServerStream owner;

		public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize)
		{
			IntPtr r, w;
			SecurityAttributesHack att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
			if (!Win32Marshal.CreatePipe (out r, out w, ref att, bufferSize))
				throw new Win32Exception (Marshal.GetLastWin32Error ());

			var rh = new SafePipeHandle (r, true);
			var wh = new SafePipeHandle (w, true);

			if (direction == PipeDirection.Out) {
				server_handle = wh;
				client_handle = rh;
			} else {
				server_handle = rh;
				client_handle = wh;
			}
		}
Exemplo n.º 20
0
    public static async Task ServerSendsByteClientReceivesAsync()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Assert.True(server.IsConnected);
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(server.GetClientHandleAsString()))
            {
                Assert.True(server.IsConnected);
                Assert.True(client.IsConnected);

                byte[] sent = new byte[] { 123 };
                byte[] received = new byte[] { 0 };
                await server.WriteAsync(sent, 0, 1);

                Assert.Equal(1, await client.ReadAsync(received, 0, 1));
                Assert.Equal(sent[0], received[0]);
            }
        }
    }
    public static void ClientSendsByteServerReceives()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Assert.True(server.IsConnected);
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.Out, server.ClientSafePipeHandle))
            {
                Assert.True(server.IsConnected);
                Assert.True(client.IsConnected);

                byte[] sent = new byte[] { 123 };
                byte[] received = new byte[] { 0 };
                client.Write(sent, 0, 1);
                int bytesReceived = server.Read(received, 0, 1);
                Assert.Equal(1, bytesReceived);
                Assert.Equal(sent[0], received[0]);
            }
        }
    }
Exemplo n.º 22
0
        public void StartChildProcess()
        {
            System.Diagnostics.Debug.Assert(null == childProcess);

            childProcess = new Process();
            childProcess.StartInfo.FileName = "FlacDecodeCS.exe";

            pss = new AnonymousPipeServerStream(
                PipeDirection.In, HandleInheritability.Inheritable);

            childProcess.StartInfo.Arguments = pss.GetClientHandleAsString();
            childProcess.StartInfo.UseShellExecute        = false;
            childProcess.StartInfo.CreateNoWindow         = true;
            childProcess.StartInfo.RedirectStandardInput  = true;
            childProcess.StartInfo.RedirectStandardOutput = false;
            childProcess.Start();

            pss.DisposeLocalCopyOfClientHandle();
            br = new BinaryReader(pss);
        }
Exemplo n.º 23
0
    public static void ServerSendsByteClientReceives()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Assert.True(server.IsConnected);
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.GetClientHandleAsString()))
            {
                Assert.True(server.IsConnected);
                Assert.True(client.IsConnected);

                byte[] sent = new byte[] { 123 };
                byte[] received = new byte[] { 0 };
                server.Write(sent, 0, 1);

                Assert.Equal(1, client.Read(received, 0, 1));
                Assert.Equal(sent[0], received[0]);
            }
            Assert.Throws<System.IO.IOException>(() => server.WriteByte(5));
        }
    }
Exemplo n.º 24
0
        public async Task AnonymousPipeReadViaFileStream(bool asyncReads)
        {
            using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                Task serverTask = server.WriteAsync(new byte[] { 0, 1, 2, 3, 4, 5 }, 0, 6);

                using (var client = new FileStream(new SafeFileHandle(server.ClientSafePipeHandle.DangerousGetHandle(), false), FileAccess.Read, bufferSize: 3))
                {
                    var arr = new byte[1];
                    for (int i = 0; i < 6; i++)
                    {
                        Assert.Equal(1, asyncReads ?
                            await client.ReadAsync(arr, 0, 1) :
                            client.Read(arr, 0, 1));
                        Assert.Equal(i, arr[0]);
                    }
                }

                await serverTask;
            }
        }
Exemplo n.º 25
0
        public void PingPong()
        {
            // Create two anonymous pipes, one for each direction of communication.
            // Then spawn another process to communicate with.
            using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            using (var remote = RemoteInvoke(PingPong_OtherProcess, outbound.GetClientHandleAsString(), inbound.GetClientHandleAsString()))
            {
                // Close our local copies of the handles now that we've passed them of to the other process
                outbound.DisposeLocalCopyOfClientHandle();
                inbound.DisposeLocalCopyOfClientHandle();

                // Ping-pong back and forth by writing then reading bytes one at a time.
                for (byte i = 0; i < 10; i++)
                {
                    outbound.WriteByte(i);
                    int received = inbound.ReadByte();
                    Assert.Equal(i, received);
                }
            }
        }
Exemplo n.º 26
0
    public static void ServerSendsByteClientReceivesAsync()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Assert.True(server.IsConnected);
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(server.GetClientHandleAsString()))
            {
                Assert.True(server.IsConnected);
                Assert.True(client.IsConnected);

                byte[] sent = new byte[] { 123 };
                byte[] received = new byte[] { 0 };
                Task writeTask = server.WriteAsync(sent, 0, 1);
                writeTask.Wait();

                Task<int> readTask = client.ReadAsync(received, 0, 1);
                readTask.Wait();

                Assert.Equal(1, readTask.Result);
                Assert.Equal(sent[0], received[0]);
            }
        }
    }
Exemplo n.º 27
0
        /// <summary>
        /// Sends settings from chief to worker process via anonymous control pipe.
        /// </summary>
        /// <param name="afterSettingsPipeCreated">Invoked with settings pipe handler, so the child worker process can be launched there with with handler as command line argument.</param>
        /// <param name="chiefLogReceiverPipe">Log receiver pipe settings to transfer.</param>
        /// <param name="workerSettings">Worker settings to transfer.</param>
        /// <param name="chiefProcess">Chief process.</param>
        /// <remarks>
        /// Method has 10 seconds timeout for worker process to connect to pipe and read settings.
        /// That is used to avoid blocking with controlPipe.WaitForPipeDrain() in case client failed to read settings or disconnected in the middle of sending message.
        /// </remarks>
        internal static void SendSettings(
            Action<string> afterSettingsPipeCreated,
            
            AnonymousPipeServerStream chiefLogReceiverPipe,
            ServerSettingsBase workerSettings,
            Process chiefProcess)
        {
            using (var chiefSettingsPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                afterSettingsPipeCreated(chiefSettingsPipe.GetClientHandleAsString());

                var binaryWriter = new BinaryWriter(chiefSettingsPipe);
                binaryWriter.Write(chiefLogReceiverPipe.GetClientHandleAsString());
                binaryWriter.Write((Int32)chiefProcess.Id);

                new BinaryFormatter()
                    .Serialize(chiefSettingsPipe, workerSettings);

                Thread.Sleep(10000);
                chiefSettingsPipe.DisposeLocalCopyOfClientHandle();
                binaryWriter.Dispose(); // because it disposes underlying stream.
            }
        }
        // AnonymousPipeServerStream owner;

        public Win32AnonymousPipeServer(AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize)
        {
            IntPtr r, w;
            SecurityAttributesHack att = new SecurityAttributesHack(inheritability == HandleInheritability.Inheritable);

            if (!Win32Marshal.CreatePipe(out r, out w, ref att, bufferSize))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            var rh = new SafePipeHandle(r, true);
            var wh = new SafePipeHandle(w, true);

            if (direction == PipeDirection.Out)
            {
                server_handle = wh;
                client_handle = rh;
            }
            else
            {
                server_handle = rh;
                client_handle = wh;
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Nimmt eine Antwort zu einer Anfrage entgegen.
 /// </summary>
 /// <param name="stream">Der Datenstrom, auf dem die Antwort bereitgestellt wird.</param>
 /// <returns>Die gewünschte Antwort.</returns>
 public Response ReceiveResponse( AnonymousPipeServerStream stream )
 {
     // Process
     return (Response) ReadFromPipe( stream, new XmlSerializer( ResponseType ) );
 }
Exemplo n.º 30
0
 /// <summary>
 /// Überträgt diese Anfrage in der XML Repräsentation in einen Datenstrom.
 /// </summary>
 /// <param name="stream">Der gewünschte Datenstrom.</param>
 public void SendRequest( AnonymousPipeServerStream stream )
 {
     // Forward
     SendToPipe( stream, m_Serializer, this );
 }
Exemplo n.º 31
0
        public void TestIPCProcess()
        {
            Process p = CreateProcess("ipc");

            using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            {
                p.StartInfo.Arguments += " " + outbound.GetClientHandleAsString() + " " + inbound.GetClientHandleAsString();
                p.Start();
                outbound.DisposeLocalCopyOfClientHandle();
                inbound.DisposeLocalCopyOfClientHandle();

                for (byte i = 0; i < 10; i++)
                {
                    outbound.WriteByte(i);
                    int received = inbound.ReadByte();
                    Assert.Equal(i, received);
                }

                Assert.True(p.WaitForExit(WaitInMS));
                Assert.Equal(SuccessExitCode, p.ExitCode);
            }
        }
Exemplo n.º 32
0
        // AnonymousPipeServerStream owner;

        public UnixAnonymousPipeServer(AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize)
        {
            // this.owner = owner;

            throw new NotImplementedException();
        }
 public Win32AnonymousPipeServer(AnonymousPipeServerStream owner, SafePipeHandle serverHandle, SafePipeHandle clientHandle)
 {
     // this.owner = owner;
     this.server_handle = serverHandle;
     this.client_handle = clientHandle;
 }