Beispiel #1
0
        private static void AnonymousPipe(AnonymousPipeServerStream outPipe,
                                          AnonymousPipeServerStream inPipe)
        {
            var clientExePath = @"..\..\..\..\CStutorial\bin\Debug\CStutorial.exe";
            var path          = Path.GetFullPath(clientExePath);

            try
            {
                var outId = outPipe.GetClientHandleAsString();
                var inId  = inPipe.GetClientHandleAsString();

                var command   = string.Format("{0} {1}", outId, inId);
                var startInfo = new ProcessStartInfo(clientExePath, command);
                startInfo.UseShellExecute = false;
                Process?process = Process.Start(startInfo);

                outPipe.DisposeLocalCopyOfClientHandle();
                inPipe.DisposeLocalCopyOfClientHandle();

                for (int i = 0; i < 1000; i++)
                {
                    var v = (byte)new Random().Next(0, 150);
                    Console.WriteLine(v);
                    outPipe.WriteByte(v);
                }

                process?.WaitForExit();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            try
            {
                // Debug.
                Console.WriteLine("Anonymous Pipes Server Begin: {0}", System.DateTime.Now.ToString());

                // Path to client executable.
                string clientPath = @"C:\Source\AV\CSharp\Streams\AnonymousPipes\AnonymousPipesClient.exe";

                HandleInheritability inherit = HandleInheritability.Inheritable;

                using (var svr = new AnonymousPipeServerStream(PipeDirection.Out, inherit))
                    using (var clt = new AnonymousPipeServerStream(PipeDirection.In, inherit))
                    {
                        string svrID = svr.GetClientHandleAsString();
                        string cltID = clt.GetClientHandleAsString();

                        ProcessStartInfo prc = new ProcessStartInfo
                        {
                            FileName        = clientPath,
                            Arguments       = svrID + " " + cltID,
                            UseShellExecute = false
                        };
                        Process.Start(prc);

                        // var startInfo = new ProcessStartInfo(clientPath, svrID + " " + cltID);
                        // startInfo.UseShellExecute = false;
                        // Process p =  Process.Start(startInfo);

                        svr.DisposeLocalCopyOfClientHandle();
                        clt.DisposeLocalCopyOfClientHandle();

                        svr.WriteByte(101);
                        Console.WriteLine($"Transmission received: {clt.ReadByte()}");

                        //prc.WaitForExit();
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source);
            }

            // Debug.
            Console.WriteLine("Anonymous Pipes Client End: {0}", System.DateTime.Now.ToString());

            // Await user input.
            Console.ReadLine();
        }
Beispiel #3
0
        public static void ServerReadOnlyThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Assert.Throws <NotSupportedException>(() => server.Write(new byte[5], 0, 5));

                Assert.Throws <NotSupportedException>(() => server.WriteByte(123));

                Assert.Throws <NotSupportedException>(() => server.Flush());

                Assert.Throws <NotSupportedException>(() => server.OutBufferSize);

                Assert.Throws <NotSupportedException>(() => server.WaitForPipeDrain());
            }
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            try
            {
                // Debug.
                Console.WriteLine("Anonymous Pipes Client Begin: {0}", System.DateTime.Now.ToString());

                //string cltID = args[0];
                //string svrID = args[1];

                // Debug.
                Console.WriteLine($"args.Length: {args.Length}");

                // Debug.
                if (args.Length > 0)
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        Console.WriteLine($"args[{i}]: {args[i].ToString()}");
                    }
                }

                // Debug.
                Console.WriteLine("Line #40");

                using (var clt = new AnonymousPipeServerStream(PipeDirection.In, inherit))
                    using (var svr = new AnonymousPipeServerStream(PipeDirection.Out, inherit))
                    {
                        // Debug.
                        Console.WriteLine("AnonymousPipesClient.cs :: Line #46");

                        Console.WriteLine($"Transmission received: {clt.ReadByte()}");
                        svr.WriteByte(200);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source);
            }

            // Debug.
            Console.WriteLine("Anonymous Pipes Client End: {0}", System.DateTime.Now.ToString());
        }
    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));
        }
    }
Beispiel #6
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);
                        }
                    }
        }
Beispiel #7
0
        public static void ClonedServer_ActsAsOriginalServer()
        {
            using (AnonymousPipeServerStream serverBase = new AnonymousPipeServerStream(PipeDirection.Out))
                using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out, serverBase.SafePipeHandle, serverBase.ClientSafePipeHandle))
                {
                    Assert.True(server.IsConnected);
                    using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
                    {
                        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 <IOException>(() => server.WriteByte(5));
                }
        }
        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);
                }
            }
        }
Beispiel #9
0
    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();
    }
        public static void ClonedServer_ActsAsOriginalServer()
        {
            using (AnonymousPipeServerStream serverBase = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out, serverBase.SafePipeHandle, serverBase.ClientSafePipeHandle))
                {
                    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<IOException>(() => server.WriteByte(5));
                }
            }
        }
Beispiel #11
0
        public void Process_IPC()
        {
            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);
                }
        }
        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 = RemoteExecutor.Invoke(new Func <string, string, int>(ChildFunc), 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);
                        }
                    }

            int ChildFunc(string inHandle, string outHandle)
            {
                // Create the clients associated with the supplied handles
                using (var inbound = new AnonymousPipeClientStream(PipeDirection.In, inHandle))
                    using (var outbound = new AnonymousPipeClientStream(PipeDirection.Out, outHandle))
                    {
                        // Repeatedly read then write a byte from and to the server
                        for (int i = 0; i < 10; i++)
                        {
                            int b = inbound.ReadByte();
                            outbound.WriteByte((byte)b);
                        }
                    }
                return(RemoteExecutor.SuccessExitCode);
            }
        }
Beispiel #13
0
        public void CtorAndAccept_SocketNotKeptAliveViaInheritance(bool validateClientOuter, int acceptApiOuter)
        {
            // 300 ms should be long enough to connect if the socket is actually present & listening.
            const int ConnectionTimeoutMs = 300;

            // Run the test in another process so as to not have trouble with other tests
            // launching child processes that might impact inheritance.
            RemoteExecutor.Invoke((validateClientString, acceptApiString) =>
            {
                bool validateClient = bool.Parse(validateClientString);
                int acceptApi       = int.Parse(acceptApiString);

                // Create a listening server.
                using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    listener.Listen();
                    EndPoint ep = listener.LocalEndPoint;

                    // Create a client and connect to that listener.
                    using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        client.Connect(ep);

                        // Accept the connection using one of multiple accept mechanisms.
                        Socket server =
                            acceptApi == 0 ? listener.Accept() :
                            acceptApi == 1 ? listener.AcceptAsync().GetAwaiter().GetResult() :
                            acceptApi == 2 ? Task.Factory.FromAsync(listener.BeginAccept, listener.EndAccept, null).GetAwaiter().GetResult() :
                            throw new Exception($"Unexpected {nameof(acceptApi)}: {acceptApi}");

                        // Get streams for the client and server, and create a pipe that we'll use
                        // to communicate with a child process.
                        using (var serverStream = new NetworkStream(server, ownsSocket: true))
                            using (var clientStream = new NetworkStream(client, ownsSocket: true))
                                using (var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                                {
                                    // Create a child process that blocks waiting to receive a signal on the anonymous pipe.
                                    // The whole purpose of the child is to test whether handles are inherited, so we
                                    // keep the child process alive until we're done validating that handles close as expected.
                                    using (RemoteExecutor.Invoke(clientPipeHandle =>
                                    {
                                        using (var clientPipe = new AnonymousPipeClientStream(PipeDirection.In, clientPipeHandle))
                                        {
                                            Assert.Equal(42, clientPipe.ReadByte());
                                        }
                                    }, serverPipe.GetClientHandleAsString()))
                                    {
                                        if (validateClient) // Validate that the child isn't keeping alive the "new Socket" for the client
                                        {
                                            // Send data from the server to client, then validate the client gets EOF when the server closes.
                                            serverStream.WriteByte(84);
                                            Assert.Equal(84, clientStream.ReadByte());
                                            serverStream.Close();
                                            Assert.Equal(-1, clientStream.ReadByte());
                                        }
                                        else // Validate that the child isn't keeping alive the "listener.Accept" for the server
                                        {
                                            // Send data from the client to server, then validate the server gets EOF when the client closes.
                                            clientStream.WriteByte(84);
                                            Assert.Equal(84, serverStream.ReadByte());
                                            clientStream.Close();
                                            Assert.Equal(-1, serverStream.ReadByte());
                                        }

                                        // And validate that we after closing the listening socket, we're not able to connect.
                                        listener.Dispose();
                                        using (var tmpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                                        {
                                            bool connected = tmpClient.TryConnect(ep, ConnectionTimeoutMs);

                                            // Let the child process terminate.
                                            serverPipe.WriteByte(42);

                                            Assert.False(connected);
                                        }
                                    }
                                }
                    }
                }
            }, validateClientOuter.ToString(), acceptApiOuter.ToString()).Dispose();
        }
        public static void ServerReadOnlyThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Assert.Throws<NotSupportedException>(() => server.Write(new byte[5], 0, 5));

                Assert.Throws<NotSupportedException>(() => server.WriteByte(123));

                Assert.Throws<NotSupportedException>(() => server.Flush());

                Assert.Throws<NotSupportedException>(() => server.OutBufferSize);

                Assert.Throws<NotSupportedException>(() => server.WaitForPipeDrain());

                Assert.Throws<NotSupportedException>(() => NotReachable(server.WriteAsync(new byte[5], 0, 5)));
            }
        }