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(); } }
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); } }
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'); } } }
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."); }
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"); }
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(); }
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); } } }
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); } }
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 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 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)); } }
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); }
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); } } }
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]); } } }
/// <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. } }
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(); } }
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; }
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]); } }
static void Relaunch() { var tempdir = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() ); Directory.CreateDirectory( tempdir ); var xcopy_args = String.Format( "/E \"{0}\" \"{1}\\\"", Path.GetDirectoryName(OriginalPath).Replace("file:\\",""), tempdir ); var pcopy = Process.Start( "xcopy", xcopy_args ); if (!pcopy.WaitForExit(10000)) throw new InvalidOperationException("Relaunch copy hanged!"); Win32.MoveFileEx( tempdir, null, Win32.MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT) ; var newexe = Path.Combine( tempdir, Path.GetFileName(OriginalPath) ); if ( Connection != null && Connection.Socket.Connected ) { var pipe = new AnonymousPipeServerStream( PipeDirection.Out, HandleInheritability.Inheritable ); var pipename = pipe.GetClientHandleAsString(); var pcloneinfo = new ProcessStartInfo( newexe, string.Format( "--original={0} --pipe={1}", OriginalPath, pipename ) ); pcloneinfo.UseShellExecute = false; var pclone = Process.Start(pcloneinfo); var sockinfo = Connection.Socket.DuplicateAndClose(pclone.Id).ProtocolInformation; pipe.Write( sockinfo, 0, sockinfo.Length ); pipe.WaitForPipeDrain(); pipe.Close(); } else { var pclone = Process.Start( newexe, string.Format( "--original={0}", OriginalPath ) ); } }
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 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); } }
/// <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 } }
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(); } }
/// <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); }
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 void FlushCanBeUsedOnPipes_Success(bool? flushToDisk) { using (var pipeStream = new AnonymousPipeServerStream(PipeDirection.In)) 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)) { Flush(fs, flushToDisk); } } }
//MAIN private NKRemotingProxy(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken) { this.context = context; this._localHandlers = null; this.ns = ns; this.cancelToken = cancelToken; var exe = System.Reflection.Assembly.GetEntryAssembly().Location; var path = System.IO.Path.GetDirectoryName(exe); ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo; startInfo.FileName = exe; startInfo.WorkingDirectory = path; startInfo.UseShellExecute = false; var syncPipeOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); var syncPipeIn = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable); var pipeOutHandle = syncPipeOut.GetClientHandleAsString(); var pipeInHandle = syncPipeIn.GetClientHandleAsString(); this.syncPipeOut = syncPipeOut; this.syncPipeIn = syncPipeIn; startInfo.Arguments = "NKR=" + buildInitMessage(pipeOutHandle, pipeInHandle); this.id = id; process = Process.Start(startInfo); NKEventEmitter.global.emit<string>("NKS.ProcessAdded", id, false); process.EnableRaisingEvents = true; process.Exited += Process_Exited; var pipeName = Convert.ToBase64String(getUniqueKey()); var asyncPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough); this.asyncPipe = asyncPipe; NKScriptChannel.nativeFirstSequence -= 5; string nativeFirstSeq = NKScriptChannel.nativeFirstSequence.ToString(); var handshake = new NKRemotingMessage(); handshake.command = NKRemotingMessage.Command.NKRemotingHandshake; handshake.args = new string[] { pipeName, ns, id, nativeSeqMax.ToString() }; syncPipeOut.WriteByte(100); syncPipeOut.Flush(); syncPipeOut.WaitForPipeDrain(); syncPipeOut.DisposeLocalCopyOfClientHandle(); syncPipeIn.DisposeLocalCopyOfClientHandle(); writeObject(syncPipeOut, handshake); syncPipeOut.WaitForPipeDrain(); var handshakeReply = readObject(syncPipeIn); if (handshakeReply == null || handshakeReply.command != NKRemotingMessage.Command.NKRemotingHandshake) Environment.Exit(911); asyncPipe.WaitForConnection(); cancelToken.Register(requestClientTeardown); var nkready = readObject(asyncPipe); if (nkready == null || nkready.command != NKRemotingMessage.Command.NKRemotingReady) Environment.Exit(910); Task.Factory.StartNew((s)=> _processServerMessages(asyncPipe), null, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default); NKEventEmitter.global.forward<NKEvent>(eventForwarderFromMain); }
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); } }
public SubProcessServer(string executablePath, RequestHandler handler) : base(handler) { PipeToClient = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); PipeFromClient = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable); Initialize(PipeFromClient, PipeToClient); Client = new Process(); Client.StartInfo.FileName = executablePath; Client.StartInfo.Arguments = PipeToClient.GetClientHandleAsString() + " " + PipeFromClient.GetClientHandleAsString(); Client.StartInfo.UseShellExecute = false; }