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());
                }
            }
        }
Ejemplo n.º 2
0
        //Fonction permettant de lire les primitives envoyées par la couche Réseau
        public void lire_de_reseau()
        {
            string commande = "";

            try{
                char c;
                do
                {
                    c = (char)transportIn.ReadByte();

                    //Si on a pas atteint le caractère de fin de primitive
                    if (c != Constantes.FIN_PRIMITIVE)
                    {
                        commande += c;                          //Alors on ajoute le caractère lu dans la chaîne de caractère
                    }
                    else
                    {
                        TraiterCommandeDeReseau(commande);                              //Sinon on envoie la chaîne dans la fonction qui traitera celle-ci
                    }
                }while(c != Constantes.FIN_PRIMITIVE);
            }catch (IOException e) {
                //Affichage du message d'erreur s'il y en a un
                Utility.AfficherDansConsole(e.Message, Constantes.ERREUR_COLOR);
            }
        }
Ejemplo n.º 3
0
        //Fonction permettant de faire la lecture du pipe venant de transport
        public void lire_de_transport()
        {
            string paquet = "";

            try{
                char c;
                do
                {
                    c = (char)reseauIn.ReadByte();

                    //Si on a pas atteint le caractère de fin de primitive
                    if (c != Constantes.FIN_PRIMITIVE)
                    {
                        paquet += c;                            //On ajoute le caractère lu dans la chaîne
                    }
                    else
                    {
                        traiterPrimitiveDeTransport(paquet);                            //Sinon on envoi la primitive lue dans une fonction qui la traitera
                    }
                }while(c != Constantes.FIN_PRIMITIVE);
            }catch (IOException e) {
                //Affichage du message d'erreur, s'il y a lieu
                Utility.AfficherDansConsole(e.Message, Constantes.ERREUR_COLOR);
            }
        }
Ejemplo n.º 4
0
        static int Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0].Equals("infinite"))
                {
                    // To avoid potential issues with orphaned processes (say, the test exits before
                    // exiting the process), we'll say "infinite" is actually 100 seconds.
                    Sleep(100 * 1000);
                }
                else if (args[0].Equals("error"))
                {
                    Console.Error.WriteLine(Name + " started error stream");
                    Console.Error.WriteLine(Name + " closed error stream");
                    Sleep();
                }
                else if (args[0].Equals("input"))
                {
                    string str = Console.ReadLine();
                }
                else if (args[0].Equals("stream"))
                {
                    Console.WriteLine(Name + " started");
                    Console.WriteLine(Name + " closed");
                    Sleep();
                }
                else if (args[0].Equals("byteAtATime"))
                {
                    var stdout = Console.OpenStandardOutput();
                    var bytes  = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a");

                    for (int i = 0; i != bytes.Length; ++i)
                    {
                        stdout.WriteByte(bytes[i]);
                        stdout.Flush();
                        Sleep(100);
                    }
                }
                else if (args[0].Equals("ipc"))
                {
                    using (var inbound = new AnonymousPipeClientStream(PipeDirection.In, args[1]))
                        using (var outbound = new AnonymousPipeClientStream(PipeDirection.Out, args[2]))
                        {
                            // Echo 10 bytes from inbound to outbound
                            for (int i = 0; i < 10; i++)
                            {
                                int b = inbound.ReadByte();
                                outbound.WriteByte((byte)b);
                            }
                        }
                }
                else
                {
                    Console.WriteLine(string.Join(" ", args));
                }
            }
            return(100);
        }
Ejemplo n.º 5
0
    public static void Main(string[] args)
    {
        PipeStream pipeClient =
            new AnonymousPipeClientStream(PipeDirection.In, args[0]);
        var from_pipe = pipeClient.ReadByte();

        Console.WriteLine("[Client]");
        Console.WriteLine(from_pipe);
    }
Ejemplo n.º 6
0
 private static int PingPong_OtherProcess(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(SuccessExitCode);
 }
 private static int PingPong_OtherProcess(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 SuccessExitCode;
 }
Ejemplo n.º 8
0
        private static void AnonymousPipeClientStreamEg(string[] args)
        {
            /*
             * Check the server side of this example similar to NamedPipeServer.
             * */

            /*
             * AnonymousPipe is similar to NamedPipe, which allows two processes
             * to communicate with each other, with difference being that
             *
             * NamedPipes are bidirectional and AnonymousPipe are unidirectional,
             * were the server sends a request to the client, and it seems like
             * the client process is a dependent process.
             * */

            /*
             * NamedPipe works by looking for a process with the same matching the
             * assigned name, were as the AnonPipe uses the ID (PID) to find the
             * process.
             * */

            try
            {
                var outId = args[0];
                var inId  = args[1];
                Console.WriteLine(outId);
                Console.WriteLine(inId);
                using (var inPipe = new AnonymousPipeClientStream(PipeDirection.In, inId))
                    using (var outPipe = new AnonymousPipeClientStream(PipeDirection.Out, outId))
                    {
                        for (int i = 0; i < 1000; i++)
                        {
                            Console.WriteLine("R: " + inPipe.ReadByte());
                            var number = new Random().Next(0, 150);
                            Console.WriteLine("S: " + number);
                            inPipe.WriteByte((byte)number);
                        }
                    }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
        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);
            }
        }
Ejemplo n.º 10
0
        static int Main(string[] args)
        {
            InChildProcess = true;

            // Terminate this process if the parent exits.
            Task.Run(() =>
            {
                try
                {
                    using (var pipeSense = new AnonymousPipeClientStream(PipeDirection.In, args[1]))
                    {
                        while (pipeSense.ReadByte() >= 0)
                        {
                            ;
                        }
                    }
                }
                finally
                {
                    Environment.Exit(5);
                }
            });

            using var pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, args[0]);

            string assemblyPath = args[2];
            string typeName     = args[3];
            string methodName   = args[4];

            Assembly asm = Assembly.LoadFrom(assemblyPath !);

            Assert.NotNull(asm);

            MethodInfo?methodInfo = asm.GetType(typeName)?.GetMethod(methodName);

            Assert.NotNull(asm);

            var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());

            runner.Load(asm, new Dictionary <string, object>());

            var result = runner.Run(TestListener.NULL, new SpecificTestFilter {
                TheMethod = methodInfo
            });

            while (result.HasChildren)
            {
                result = result.Children.Single();
            }

            // If nothing was tested, don't output the empty success result.
            if (result == null || result.Test?.Method?.MethodInfo != methodInfo)
            {
                return(1);
            }

            XmlSerializer xmlserializer = new(typeof(FakeTestResult));

            XmlWriterSettings settings = new();

            using (XmlWriter writer = XmlWriter.Create(pipeClient, settings))
            {
                xmlserializer.Serialize(writer, FakeTestResult.FromReal(result));
            }

            return(0);
        }
Ejemplo n.º 11
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();
        }
 static void ChildProcessBody(string clientPipeHandle)
 {
     using var clientPipe = new AnonymousPipeClientStream(PipeDirection.In, clientPipeHandle);
     Assert.Equal(42, clientPipe.ReadByte());
 }