DisposeLocalCopyOfClientHandle() public method

public DisposeLocalCopyOfClientHandle ( ) : void
return void
示例#1
0
文件: Program.cs 项目: merxbj/src
        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();
            }
        }
示例#2
0
文件: Program.cs 项目: gynorbi/home
        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.");
        }
示例#3
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();
 }
示例#4
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.");
        }
        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);
        }
示例#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);
                }
            }
        }
        /// <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.
            }
        }
示例#8
0
        /// <summary>
        /// The main entry point for the spawned thread. 
        /// If this method is allowed to complete, the thread will be disposed and all 
        /// memory lost.
        /// </summary>
        public void ThreadProc()
        {
            AnonymousPipeServerStream pipeServer =
                    new AnonymousPipeServerStream(PipeDirection.In,
                    HandleInheritability.Inheritable);

            Process childProcess = new Process();
            childProcess.StartInfo.FileName = this.clientProcess;
            childProcess.StartInfo.Arguments += " " + pipeServer.GetClientHandleAsString();
            childProcess.StartInfo.Arguments += " " + kinectId;

            #if (DEBUG)
            Console.WriteLine("[Thread] Setting up Kinect with ID: {0}", KinectSensor.KinectSensors[0].UniqueKinectId);
            #endif

            childProcess.StartInfo.UseShellExecute = false;
            childProcess.Start();

            pipeServer.DisposeLocalCopyOfClientHandle();

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                Skeleton[] skeletonData;

                while (pipeServer.IsConnected)
                {
                    try
                    {
                        skeletonData = (Skeleton[]) formatter.Deserialize(pipeServer);
                        List<Skeleton> toUpdate = new List<Skeleton>();

                        foreach (Skeleton s in skeletonData)
                        {
                            if (s.TrackingState == SkeletonTrackingState.Tracked)
                            {
            #if (DEBUG)
                                //Console.WriteLine("[Child] Tracking skeleton with ID: {0}", s.TrackingId);
            #endif
                                toUpdate.Add(s);
                            }
                        }

                        if (toUpdate.Count > 0)
                        {
                            UpdateSkeletons(toUpdate);
                        }
                        else
                        {
                            EmptyFrame();
                        }
                    }
                    catch (SerializationException e)
                    {
            #if (DEBUG)
                        Console.WriteLine("[Thread] Exception: {0}", e.Message);
            #else
                        throw e;
            #endif
                    }
                }
            }
            catch (IOException e)
            {
            #if (DEBUG)
                Console.WriteLine("[Thread] Error: {0}", e.Message);
            #else
                throw e;
            #endif
            }
        }
示例#9
0
        /// <summary>
        /// Constructor. Starts external process.
        /// </summary>
        /// <param name="t">The type of the external class to manage.</param>
        protected InProcessAgent(Type t)
        {
            //Fire up instance of exe, with pipes set up.
            clientProcess = new Process();
            clientProcess.StartInfo.FileName = t.Assembly.Location;
            pipeOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            pipeIn = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            clientProcess.StartInfo.Arguments = pipeOut.GetClientHandleAsString() + " " + pipeIn.GetClientHandleAsString();
            clientProcess.StartInfo.UseShellExecute = false;
            clientProcess.Start();
            pipeOut.DisposeLocalCopyOfClientHandle();
            pipeIn.DisposeLocalCopyOfClientHandle();

            //initialise an instance of the object

            messageSender = new MessageSender(pipeOut);
            messageReceiver = new MessageReceiver(pipeIn);
        }
示例#10
0
        public void ThreadProc()
        {
            AnonymousPipeServerStream pipeServer =
                    new AnonymousPipeServerStream(PipeDirection.In,
                    HandleInheritability.Inheritable);

            Process childProcess = new Process();
            childProcess.StartInfo.FileName = this.clientProcess;
            childProcess.StartInfo.Arguments += " " + pipeServer.GetClientHandleAsString();
            childProcess.StartInfo.Arguments += " " + kinectId;

            Console.WriteLine("Setting up Kinect with ID: {0}", KinectSensor.KinectSensors[0].UniqueKinectId);

            childProcess.StartInfo.UseShellExecute = false;
            childProcess.Start();

            pipeServer.DisposeLocalCopyOfClientHandle();

            try
            {
                Console.WriteLine("[Server] Ready for Skeleton data");
                BinaryFormatter formatter = new BinaryFormatter();

                Skeleton[] skeletonData;

                while (pipeServer.IsConnected)
                {
                    try
                    {
                        skeletonData = (Skeleton[]) formatter.Deserialize(pipeServer);
                        bool update = false;
                        int numTracked = 0;
                        foreach (Skeleton s in skeletonData)
                        {
                            if (s.TrackingState == SkeletonTrackingState.Tracked)
                            {
                                Console.WriteLine("Tracking skeleton with ID: {0}", s.TrackingId);
                                MotionEngine.getInstance().SkeletonFrameReady(s);
                                //numTracked++;
                                //Console.WriteLine("[Server] Tracking a skeleton with ID: {0}", s.TrackingId);
                                //AssignSkeleton(s);
                                //MultKinectServer.updateSkeleton(s);

                                //for (int i = 0; i < skeletons.Length; i++ )
                                //{
                                //    if (skeletons[i] == null)
                                //    {
                                //        skeletons[i] = s;
                                //        update = true;
                                //    }

                                //    if (s.TrackingId == skeletons[i].TrackingId)
                                //    {
                                //        skeletons[i] = s;
                                //        update = true;
                                //    }
                                //}
                            }
                        }

                        //if (update)
                        //{
                        //    MultKinectServer.updateSkeletons(skeletons, kinectId);
                        //}

                        //if (numTracked == 0)
                        //{
                        //    Console.WriteLine("Lost skeletons");
                        //    skeletons[0] = null;
                        //    skeletons[1] = null;
                        //}
                    }
                    catch (SerializationException e)
                    {
                        Console.WriteLine("[Server] Exception: {0}", e.Message);
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("[SERVER-Thread1] Error: {0}", e.Message);
            }
        }
示例#11
0
        private void DoJITTest(TestAgent test, uint milestoneCount, uint iterationCount)
        {
            var outPipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            var inPipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            var outClientHandler = outPipeServer.GetClientHandleAsString();
            var inClientHandler = inPipeServer.GetClientHandleAsString();

            var workerProcess = new Process();
            workerProcess.StartInfo.FileName = _jitesterPath;
            workerProcess.StartInfo.UseShellExecute = false;

            workerProcess.StartInfo.Arguments = String.Concat(
                outClientHandler, " ",
                inClientHandler, " ",
                milestoneCount, " ",
                iterationCount, " ",
                test.ContainerType.Assembly.Location);

            workerProcess.Start();

            outPipeServer.DisposeLocalCopyOfClientHandle();
            inPipeServer.DisposeLocalCopyOfClientHandle();

            var binFormatter = new BinaryFormatter();
            binFormatter.Serialize(outPipeServer, test);

            outPipeServer.WaitForPipeDrain();

            var resObj = binFormatter.Deserialize(inPipeServer);
            var results = resObj as List<PassResult>;

            foreach (var result in results)
            {
                _resultHandler.AddResult(result);
                _progressHandler.PortionDone();
            }
        }
示例#12
0
		Stream OpenOutput(string gitExe, string fileName, string blobHash)
		{
			if (!File.Exists(fileName))
				return null;
			if (blobHash == null)
				return null;
			
			AnonymousPipeServerStream pipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
			
			StartupInfo startupInfo = new GitVersionProvider.StartupInfo();
			startupInfo.dwFlags = STARTF_USESTDHANDLES;
			startupInfo.hStdOutput = pipe.ClientSafePipeHandle;
			startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
			startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
			startupInfo.cb = 16;
			
			PROCESS_INFORMATION procInfo;
			
			string commandLine = "\"" + gitExe + "\" cat-file blob " + blobHash;
			string workingDir = Path.GetDirectoryName(fileName);
			Debug.WriteLine(workingDir + "> " + commandLine);
			const uint CREATE_NO_WINDOW = 0x08000000;
			if (!CreateProcess(null, commandLine,
			                   IntPtr.Zero, IntPtr.Zero, true, CREATE_NO_WINDOW, IntPtr.Zero, workingDir, ref startupInfo,
			                   out procInfo)) {
				pipe.DisposeLocalCopyOfClientHandle();
				pipe.Close();
				return null;
			}
			
			pipe.DisposeLocalCopyOfClientHandle();
			
			return pipe;
		}
		Stream OpenOutput(string fileName, string blobHash)
		{
			if (blobHash == null)
				return null;
			
			AnonymousPipeServerStream pipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
			
			StartupInfo startupInfo = new GitVersionProvider.StartupInfo();
			startupInfo.dwFlags = STARTF_USESTDHANDLES;
			startupInfo.hStdOutput = pipe.ClientSafePipeHandle;
			startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
			startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
			startupInfo.cb = 16;
			
			PROCESS_INFORMATION procInfo;
			
			if (!CreateProcess(null, string.Format("cmd /c git cat-file blob {0}", blobHash),
			                   IntPtr.Zero, IntPtr.Zero, true, 0, IntPtr.Zero, Path.GetDirectoryName(fileName), ref startupInfo,
			                   out procInfo)) {
				pipe.DisposeLocalCopyOfClientHandle();
				pipe.Close();
				return null;
			}
			
			pipe.DisposeLocalCopyOfClientHandle();
			
			return pipe;
		}
示例#14
0
文件: Fifo.cs 项目: weeble/ohos
 public AnonymousPipeParent(Func<string, Process> aSpawnFunc)
 {
     var downPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
     var upPipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
     Token = downPipe.GetClientHandleAsString() + "," + upPipe.GetClientHandleAsString();
     Child = aSpawnFunc(Token);
     downPipe.DisposeLocalCopyOfClientHandle();
     upPipe.DisposeLocalCopyOfClientHandle();
     ToChild = downPipe;
     FromChild = upPipe;
 }
示例#15
0
文件: Form1.cs 项目: stankela/clanovi
        private void init()
        {
            // This creates singleton instance of NHibernateHelper and builds session factory
            NHibernateHelper nh = NHibernateHelper.Instance;

            loadOptions();

            if (Options.Instance.JedinstvenProgram)
            {
                this.Text = "Uplata clanarine";
                refreshAdminModeUI(Options.Instance.AdminMode);
                //LocalizeUI();

                Sesija.Instance.InitSession();

                initlozinkaTimer();

                initCitacKarticaDictionary();
                pokreniCitacKartica();
            }
            else if (Options.Instance.IsProgramZaClanarinu)
            {
                this.Text = "Uplata clanarine";
                refreshAdminModeUI(Options.Instance.AdminMode);
                //LocalizeUI();

                Sesija.Instance.InitSession();

                initlozinkaTimer();

                pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
                clientProcess = new Process();
                clientProcess.StartInfo.FileName = Options.Instance.ClientPath;
                // Pass the client process a handle to the server.
                clientProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                clientProcess.StartInfo.UseShellExecute = false;

                clientStarted = true;
                try
                {
                    clientProcess.Start();
                }
                catch (Exception)
                {
                    clientStarted = false;
                    MessageDialogs.showMessage("GRESKA: Ne mogu da pokrenem citac kartica '" + Options.Instance.ClientPath + "'",
                        Form1.Instance.Text);
                }
                pipeServer.DisposeLocalCopyOfClientHandle();

                if (clientStarted)
                {
                    pipeServerStreamWriter = new StreamWriter(pipeServer);
                }
            }
            else
            {
                initCitacKarticaDictionary();
                pokreniCitacKartica();
                pokreniPipeClientThread();
            }
        }
        public async static Task<COMEnumerateInterfaces> GetInterfacesOOP(COMCLSIDEntry ent)
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(System.IO.Pipes.PipeDirection.In,
                HandleInheritability.Inheritable, 16 * 1024, null))
            {
                string process = null;
                if (!Environment.Is64BitOperatingSystem || Environment.Is64BitProcess)
                {
                    process = COMUtilities.GetExePath();
                }
                else
                {
                    process = COMUtilities.Get32bitExePath();
                }

                string apartment = "s";
                if (ent.ThreadingModel == COMThreadingModel.Both 
                    || ent.ThreadingModel == COMThreadingModel.Free)
                {
                    apartment = "m";
                }

                Process proc = new Process();
                ProcessStartInfo info = new ProcessStartInfo(process, String.Format("{0} {1} {2} {3} \"{4}\"",
                    "-e", server.GetClientHandleAsString(), ent.Clsid.ToString("B"), apartment, ent.CreateContext));
                info.UseShellExecute = false;
                info.CreateNoWindow = true;
                proc.StartInfo = info;
                proc.Start();
                try
                {
                    server.DisposeLocalCopyOfClientHandle();

                    using (StreamReader reader = new StreamReader(server))
                    {
                        List<COMInterfaceInstance> interfaces = new List<COMInterfaceInstance>();
                        List<COMInterfaceInstance> factory_interfaces = new List<COMInterfaceInstance>();
                        while (true)
                        {
                            string line = await reader.ReadLineAsync();
                            if (line == null)
                            {
                                break;
                            }

                            if (line.StartsWith("ERROR:"))
                            {
                                uint errorCode;
                                try
                                {
                                    errorCode = uint.Parse(line.Substring(6), System.Globalization.NumberStyles.AllowHexSpecifier);
                                }
                                catch (FormatException ex)
                                {
                                    Debug.WriteLine(ex.ToString());
                                    errorCode = 0x80004005;
                                }

                                throw new Win32Exception((int)errorCode);
                            }
                            else
                            {
                                Guid g;
                                bool factory = false;

                                if (line.StartsWith("*"))
                                {
                                    factory = true;
                                    line = line.Substring(1);
                                }

                                string[] parts = line.Split(new char[] { ',' }, 3);
                                if (Guid.TryParse(parts[0], out g))
                                {
                                    string module_path = null;
                                    long vtable_offset = 0;
                                    if (parts.Length == 3)
                                    {
                                        module_path = parts[1];
                                        long.TryParse(parts[2], out vtable_offset);
                                    }

                                    if (factory)
                                    {
                                        factory_interfaces.Add(new COMInterfaceInstance(g, module_path, vtable_offset));
                                    }
                                    else
                                    {
                                        interfaces.Add(new COMInterfaceInstance(g, module_path, vtable_offset));
                                    }
                                }
                            }
                        }

                        if (!proc.WaitForExit(5000))
                        {
                            proc.Kill();
                        }
                        int exitCode = proc.ExitCode;
                        if (exitCode != 0)
                        {
                            interfaces = new List<COMInterfaceInstance>(new COMInterfaceInstance[] { new COMInterfaceInstance(COMInterfaceEntry.IID_IUnknown) });
                            factory_interfaces = new List<COMInterfaceInstance>(new COMInterfaceInstance[] { new COMInterfaceInstance(COMInterfaceEntry.IID_IUnknown) });
                        }

                        return new COMEnumerateInterfaces(ent.Clsid, ent.CreateContext, interfaces, factory_interfaces);
                    }
                }
                finally
                {
                    proc.Close();
                }
            }
        }
    public static void ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Task clientTask = StartClientAsync(PipeDirection.In, server.ClientSafePipeHandle);

            Console.WriteLine("server.CanRead = {0}", server.CanRead);
            Console.WriteLine("server.CanSeek = {0}", server.CanSeek);
            Console.WriteLine("server.CanTimeout = {0}", server.CanTimeout);
            Console.WriteLine("server.CanWrite = {0}", server.CanWrite);
            Console.WriteLine("server.GetClientHandleAsString() = {0}", server.GetClientHandleAsString());
            Console.WriteLine("server.IsAsync = {0}", server.IsAsync);
            Console.WriteLine("server.IsConnected = {0}", server.IsConnected);
            Console.WriteLine("server.OutBufferSize = {0}", server.OutBufferSize);
            Console.WriteLine("server.ReadMode = {0}", server.ReadMode);
            Console.WriteLine("server.SafePipeHandle = {0}", server.SafePipeHandle);
            Console.WriteLine("server.TransmissionMode = {0}", server.TransmissionMode);
            server.Write(new byte[] { 123 }, 0, 1);
            server.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
            server.Flush();
            Console.WriteLine("Waiting for Pipe Drain.");
            server.WaitForPipeDrain();
            clientTask.Wait();
            server.DisposeLocalCopyOfClientHandle();
        }
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Task clientTask = StartClientAsync(PipeDirection.Out, server.ClientSafePipeHandle);

            Console.WriteLine("server.InBufferSize = {0}", server.InBufferSize);
            byte[] readData = new byte[] { 0, 1 };
            server.Read(readData, 0, 1);
            server.ReadAsync(readData, 1, 1).Wait();
            Assert.Equal(123, readData[0]);
            Assert.Equal(124, readData[1]);
        }
    }
    public static void ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.In, server.ClientSafePipeHandle));

            Assert.False(server.CanRead);
            Assert.False(server.CanSeek);
            Assert.False(server.CanTimeout);
            Assert.True(server.CanWrite);
            Assert.False(string.IsNullOrWhiteSpace(server.GetClientHandleAsString()));
            Assert.False(server.IsAsync);
            Assert.True(server.IsConnected);
            if (Interop.IsWindows)
            {
                Assert.Equal(0, server.OutBufferSize);
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => server.OutBufferSize);
            }
            Assert.Equal(PipeTransmissionMode.Byte, server.ReadMode);
            Assert.NotNull(server.SafePipeHandle);
            Assert.Equal(PipeTransmissionMode.Byte, server.TransmissionMode);

            server.Write(new byte[] { 123 }, 0, 1);
            server.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
            server.Flush();
            if (Interop.IsWindows)
            {
                server.WaitForPipeDrain();
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => server.WaitForPipeDrain());
            }

            clientTask.Wait();
            server.DisposeLocalCopyOfClientHandle();
        }

        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.Out, server.ClientSafePipeHandle));

            if (Interop.IsWindows)
            {
                Assert.Equal(4096, server.InBufferSize);
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize);
            }
            byte[] readData = new byte[] { 0, 1 };
            Assert.Equal(1, server.Read(readData, 0, 1));
            Assert.Equal(1, server.ReadAsync(readData, 1, 1).Result);
            Assert.Equal(123, readData[0]);
            Assert.Equal(124, readData[1]);

            clientTask.Wait();
        }
    }
    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());
        }
    }
示例#20
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);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            Process pipeClient = new Process();

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

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

                LogItLine(string.Format("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.
                        SendMessage(pipeServer, sw, "SYNC");
                        // Send the console input to the client process.
                        for (int i = 0; i < 5; i++)
                        {
                            SendMessage(pipeServer, sw, string.Format("Message {0}", i));
                        }
                        // Send a 'sync message' and wait for client to receive it.
                        SendMessage(pipeServer, sw, "END");
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    LogItLine(string.Format("Error: {0}", e.Message));
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            LogIt("Client quit. Server terminating.");
            Console.ReadKey();
        }