コード例 #1
0
        private static Process GetProcess(Runtime runtime)
        {
            Process proc = null;

            try
            {
                proc = new Process();
                proc.StartInfo.WorkingDirectory = runtime.Equals(Runtime.CSharp) ?
                                                  CSHARP_CLIENT_WORKING_DIR : PYTHON_INTERPRETER_WORKING_DIR;
                proc.StartInfo.FileName = runtime.Equals(Runtime.CSharp) ?
                                          Path.Join(CSHARP_CLIENT_WORKING_DIR, CSHARP_CLIENT_FILE_NAME) :
                                          Path.Join(PYTHON_INTERPRETER_WORKING_DIR, PYTHON_INTERPRETER);
                proc.StartInfo.UseShellExecute = false;

                proc.StartInfo.Arguments = runtime.Equals(Runtime.CSharp) ?
                                           $"{_sender.GetClientHandleAsString()} {_receiver.GetClientHandleAsString()}" :
                                           $"{PYTHON_SCRIPT} {_sender.GetClientHandleAsString()} {_receiver.GetClientHandleAsString()}";

                proc.StartInfo.RedirectStandardError  = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(OutputResponse);
                proc.ErrorDataReceived  += new DataReceivedEventHandler(ErrorResponse);
                proc.Start();
            }
            catch (Exception e)
            {
                proc.Kill();
                proc.Close();
                throw e;
            }
            return(proc);
        }
コード例 #2
0
        static void Write()
        {
            //客户端程序路径
            string  clientFile = @"D:\CoCo\GitHub\PipesX\PipesX\Anonymous.Client\bin\Debug\Anonymous.Client.exe";
            Process process    = new Process();

            process.StartInfo.FileName = clientFile;
            //创建匿名管道流实例,
            using (AnonymousPipeServerStream pipeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                //将句柄传递给子进程
                process.StartInfo.Arguments       = pipeStream.GetClientHandleAsString();
                process.StartInfo.UseShellExecute = false;
                process.Start();
                //销毁子进程的客户端句柄?
                pipeStream.DisposeLocalCopyOfClientHandle();

                using (StreamWriter sw = new StreamWriter(pipeStream))
                {
                    string line;
                    while ((line = Console.ReadLine()) != "stop")
                    {
                        sw.AutoFlush = true;
                        //向匿名管道中写入内容
                        sw.WriteLine(line);
                    }
                }
            }
            process.WaitForExit();
            process.Close();
        }
コード例 #3
0
 public TestsDispatcher(int parallelLevel, int maxBusyRunners, bool oneTimeRunners, float killTimeFactor)
 {
     _pipeIn      = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
     _pipeOut     = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
     _pipeCmd     = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
     _streamIn    = new StreamReader(_pipeIn);
     _streamOut   = new StreamWriter(_pipeOut);
     _streamCmd   = new StreamWriter(_pipeCmd);
     _coreProcess = new Process
     {
         StartInfo =
         {
             FileName        = DISPATCHER_NAME,
             UseShellExecute = false,
             Arguments       = _pipeOut.GetClientHandleAsString() + " " +
                               _pipeIn.GetClientHandleAsString() + " " +
                               _pipeCmd.GetClientHandleAsString() + " " +
                               parallelLevel + " " +
                               maxBusyRunners + " " +
                               oneTimeRunners + " " +
                               killTimeFactor
         }
     };
     _coreProcess.Start();
     _pipeCmd.DisposeLocalCopyOfClientHandle();
     _pipeOut.DisposeLocalCopyOfClientHandle();
     _pipeIn.DisposeLocalCopyOfClientHandle();
 }
コード例 #4
0
        static void Main(string[] args)
        {
            Process process = new Process();

            process.StartInfo.FileName = "ConsoleApp1.exe";
            //创建匿名管道流实例,
            using (AnonymousPipeServerStream pipeStream =
                       new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                //将句柄传递给子进程
                process.StartInfo.Arguments       = pipeStream.GetClientHandleAsString();
                process.StartInfo.UseShellExecute = false;
                process.Start();
                //销毁子进程的客户端句柄?
                pipeStream.DisposeLocalCopyOfClientHandle();

                using (StreamWriter sw = new StreamWriter(pipeStream))
                {
                    sw.AutoFlush = true;
                    //向匿名管道中写入内容
                    sw.WriteLine(Console.ReadLine());
                }
            }
            process.WaitForExit();
            process.Close();
        }
        public Form1()
        {
            InitializeComponent();
            try
            {
                mre.Reset();
                Process process = new Process();
                process.StartInfo.FileName = "cppPlayer.exe";
                //创建匿名管道流实例,

                using (pipeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                {
                    //pipeStream.
                    //将句柄传递给子进程
                    string strlhandle = mre.ToString();
                    string strpipe    = pipeStream.GetClientHandleAsString();

                    //string strPam = strlhandle + " " +
                    process.StartInfo.Arguments       = "file:///D:/123.mp3 192.168.4.90 9885 103 " + strlhandle + " " + strpipe + " 1600 128";
                    process.StartInfo.UseShellExecute = true;
                    process.Start();
                }
                //process.WaitForExit();
                //process.Close();
            }
            catch (Exception dxml)
            {
            }
        }
コード例 #6
0
        public void Run()
        {
            log.Debug("Running DesktopStrategy...");

            using (AnonymousPipeServerStream pipeServer =
                       new AnonymousPipeServerStream(PipeDirection.In,
                                                     HandleInheritability.Inheritable))
            {
                ipcProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                ipcProcess.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();
                try
                {
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        while (pipeServer.IsConnected)
                        {
                            PlayerController.RemoteCommandQueue.Enqueue(reader.ReadLine());
                        }
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine($"[CommandCenter SERVER] Error: {e.Message}");
                }
            }
        }
コード例 #7
0
ファイル: VtmDev.cs プロジェクト: frto027/IotSimulate
        /// <summary>
        /// 建立一个方向为In或者Out的匿名管道,并将管道的名字附加到-arg参数后面
        /// </summary>
        /// <param name="arg">管道名字对应的参数</param>
        /// <param name="directionIn">管道方向,true是In,即从外部输入到这里的C#,false是Out,即输出到外部</param>
        /// <returns>匿名管道(可转化为IO流)</returns>
        private AnonymousPipeServerStream CreatePipeToArgument(string arg, bool directionIn)
        {
            var r = new AnonymousPipeServerStream(directionIn ? PipeDirection.In : PipeDirection.Out, HandleInheritability.Inheritable);

            args += " -" + arg + " " + r.GetClientHandleAsString();
            return(r);
        }
コード例 #8
0
        void run()
        {
            using (pipeServer)
            {
                StartClient(pipeServer.GetClientHandleAsString());
                pipeServer.DisposeLocalCopyOfClientHandle();

                using (sw)
                {
                    sw.AutoFlush = true;
                    sw.WriteLine("SYNC");
                    pipeServer.WaitForPipeDrain();
                    while (true)
                    {
                        try
                        {
                            Evnt.WaitOne();
                            sw.WriteLine(x);
                            sw.WriteLine(y);
                            sem.Release();
                        }
                        catch (SemaphoreFullException)
                        {
                        }
                    }
                }
            }
        }
コード例 #9
0
        private void HostControl(bool ctrlStatus)
        {
            try
            {
                if (ctrlStatus) // 만약 프로세스가 돌고있는 상태가 아닐 때에만 새로운 프로세스가 생성이 되도록 설정
                {
                    pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);

                    hookerProcess = new Process
                    {
                        StartInfo = hookerProcessStartInfo
                    };
                    hookerProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                    hookerProcess.Start();
                }

                if (!ctrlStatus) // 만약 프로세스가 돌고있는 상태에서만 아래 코드가 동작을 하도록 설정
                {
                    pipeServer.DisposeLocalCopyOfClientHandle();
                    QuitProcess();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Exception : {0}", e.Message));
            }
        }
コード例 #10
0
        public void ClientClosesPipe_ServerReceivesEof()
        {
            using (var pipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                using (var remote = RemoteInvoke(new Func <string, int>(ChildFunc), pipe.GetClientHandleAsString(), new RemoteInvokeOptions {
                    CheckExitCode = false
                }))
                {
                    pipe.DisposeLocalCopyOfClientHandle();

                    for (int i = 1; i <= 5; i++)
                    {
                        Assert.Equal(i, pipe.ReadByte());
                    }
                    Assert.Equal(-1, pipe.ReadByte());

                    remote.Process.Kill();
                }

            int ChildFunc(string clientHandle)
            {
                using (var pipe = new AnonymousPipeClientStream(PipeDirection.Out, clientHandle))
                {
                    pipe.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
                }
                Thread.CurrentThread.Join();
                return(SuccessExitCode);
            }
        }
コード例 #11
0
        public void ServerClosesPipe_ClientReceivesEof()
        {
            using (var pipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                using (var remote = RemoteInvoke(new Func <string, int>(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));
                }

            int 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());
                }
                return(SuccessExitCode);
            }
        }
コード例 #12
0
        static void Read()
        {
            //客户端程序路径
            string  clientFile = @"D:\CoCo\GitHub\PipesX\PipesX\Anonymous.Client\bin\Debug\Anonymous.Client.exe";
            Process process    = new Process();

            process.StartInfo.FileName = clientFile;
            //创建匿名管道流实例,
            using (AnonymousPipeServerStream pipeStream = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            {
                //将句柄传递给子进程
                process.StartInfo.Arguments       = pipeStream.GetClientHandleAsString();
                process.StartInfo.UseShellExecute = false;
                process.Start();
                //销毁子进程的客户端句柄?
                pipeStream.DisposeLocalCopyOfClientHandle();

                using (StreamReader sr = new StreamReader(pipeStream))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine("Server Receive: {0}", line);
                    }
                }
            }
            process.WaitForExit();
            process.Close();
        }
コード例 #13
0
        //服务端
        private void Writer()
        {
            try
            {
                //把服务器充当读取器
                var pipeReader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None);
                using (var reader = new StreamReader(pipeReader))
                {
                    //获取管道的客户端句柄,被转换为一个字符串后赋予变量_pipeHandle
                    //这个变量以后有充当写入器的客户端使用
                    _pipeHandle = pipeReader.GetClientHandleAsString();
                    Console.WriteLine("pipe handle:" + _pipeHandle);
                    _pipeHandleSet.Set();

                    bool end = false;
                    while (!end)
                    {
                        string line = reader.ReadLine();
                        Console.WriteLine(line);
                        if (line == "end")
                        {
                            end = true;
                        }
                    }
                    Console.WriteLine("finished reading");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #14
0
        public void Start(ProcessStartInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            process.StartInfo = info;

            Debug.WriteLine("WorkerProcess starting...");
            string oldArguments = info.Arguments;

            try {
                info.Arguments += " " + hostToWorkerPipe.GetClientHandleAsString() + " " + workerToHostPipe.GetClientHandleAsString();
                if (!process.Start())
                {
                    throw new InvalidOperationException("Process.Start() failed");
                }
            } finally {
                info.Arguments = oldArguments;
                // client handles were inherited into started process, dispose our copy
                hostToWorkerPipe.DisposeLocalCopyOfClientHandle();
                workerToHostPipe.DisposeLocalCopyOfClientHandle();
            }
            id = process.Id;
            readerThread.Start();
            this.Writer = new BinaryWriter(hostToWorkerPipe);
            Debug.WriteLine("WorkerProcess " + id + " started");
        }
コード例 #15
0
ファイル: PipeServer.cs プロジェクト: S031/IpcChannel
        public IpcPipeServer(IpcPipeServerOptions options)
        {
            PipeReadHandle     = _pipeRead.GetClientHandleAsString();
            PipeWriteHandle    = _pipeWrite.GetClientHandleAsString();
            _cancellationToken = options.CancellationToken == default
                                ? new CancellationTokenSource().Token
                                : options.CancellationToken;

            _ewh = new EventWaitHandle(true, EventResetMode.AutoReset, $"{PipeReadHandle}-{PipeWriteHandle}");
            if (!string.IsNullOrEmpty(options.ProcessStartPath) && File.Exists(options.ProcessStartPath))
            {
                _workProcess = new Process
                {
                    StartInfo =
                    {
                        FileName        = options.ProcessStartPath,
                        CreateNoWindow  = true,
                        UseShellExecute = false,
                        Arguments       = PipeReadHandle + " " + PipeWriteHandle
                    }
                };
                _workProcess.Start();
            }
            //Call when restart process
            //_pipeRead?.DisposeLocalCopyOfClientHandle();
            //_pipeWrite?.DisposeLocalCopyOfClientHandle();
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: VijayEluri/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();
            }
        }
コード例 #17
0
 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);
     }
 }
コード例 #18
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);
            }
        }
コード例 #19
0
        public Stream GetWriteStream()
        {
            var pipeServer = new AnonymousPipeServerStream();
            var pipeClient = new AnonymousPipeClientStream(pipeServer.GetClientHandleAsString());

            Task.Factory.StartNew(() =>
            {
                using var sr = new StreamReader(pipeClient);
                using var sw = new StreamWriter(_fileStream, new UTF8Encoding(false));
                sw.WriteLine(JsonConvert.SerializeObject(_header));
                var buf = new char[1024];
                int bytesRead;
                while ((bytesRead = sr.Read(buf, 0, buf.Length)) != 0)
                {
                    var ts    = DateTimeOffset.Now - _startTimeStamp;
                    var chars = string.Join("", buf.Take(bytesRead).Select(c => c.ToString()));
                    var data  = new List <object> {
                        ts.TotalSeconds, "o", chars
                    };
                    sw.WriteLine(JsonConvert.SerializeObject(data)); // asciinema compatible
                    Console.Out.Write(buf.Take(bytesRead).ToArray());
                }

                WaitForWriter.Set();
            }, TaskCreationOptions.LongRunning);

            return(pipeServer);
        }
コード例 #20
0
        static void Main(string[] args)
        {
            int cont             = 1;
            ProcessStartInfo psi = new ProcessStartInfo();

            Console.SetCursorPosition(7, 1);
            Console.WriteLine("padre");
            for (int i = 0; i < 2; i++)
            {
                using (AnonymousPipeServerStream pipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                {
                    using (StreamWriter sw = new StreamWriter(pipe))
                    {
                        Process p = new Process();
                        psi.FileName        = "..\\..\\..\\Hijo\\bin\\Debug\\Hijo.exe";
                        psi.Arguments       = pipe.GetClientHandleAsString();
                        psi.UseShellExecute = false;
                        p.StartInfo         = psi;
                        p.Start();
                        sw.WriteLine(Process.GetCurrentProcess().Id);
                        sw.WriteLine(cont);

                        cont++;
                    }
                }
            }
            Console.ReadLine();
        }
コード例 #21
0
ファイル: ServerProcess.cs プロジェクト: TagsRocks/GladNet
        //DLLNAME APPNAME HAILMESSAGE PORT PIPEHANDLE
        public ServerProcess(string path, ConfigInformation info)
        {
            serverBroadcastingPipe =
                new AnonymousPipeServerStream(PipeDirection.Out, System.IO.HandleInheritability.Inheritable);

            serverStreamWriter = new StreamWriter(serverBroadcastingPipe);

            try
            {
                Config = info;
                string clientString = serverBroadcastingPipe.GetClientHandleAsString();

                ApplicationProcess = Process.Start(new ProcessStartInfo()
                {
                    Arguments = Config.DLLName + " " + Config.ApplicationName + " " + Config.HailMessage + " " +
                                Config.Port.ToString() + " " + clientString,
                    UseShellExecute = false,
                    FileName        = path
                });

                UniqueProcessID = ApplicationProcess.Id;

                ApplicationProcess.EnableRaisingEvents = true;

                ApplicationProcess.Exited += new EventHandler(OnExit);
            }
            catch (NullReferenceException e)
            {
                MessageBox.Show(e.Message + " " + e.Data + e.StackTrace);
            }
        }
コード例 #22
0
        /// <summary>
        ///     Record stdin
        /// </summary>
        /// <returns></returns>
        public Stream GetInputStream()
        {
            var pipeServer = new AnonymousPipeServerStream();
            var pipeClient = new AnonymousPipeClientStream(pipeServer.GetClientHandleAsString());

            return(pipeClient);
        }
コード例 #23
0
        static void Main(string[] args)
        {
            int lim = 5;

            for (int i = 0; i < 2; i++)
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                using (AnonymousPipeServerStream apcs = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                {
                    using (StreamWriter sw = new StreamWriter(apcs))
                    {
                        Process p = new Process();
                        psi.FileName        = "..\\..\\..\\Hijo\\bin\\Debug\\Hijo.exe";
                        psi.UseShellExecute = false;
                        psi.Arguments       = apcs.GetClientHandleAsString();
                        p.StartInfo         = psi;

                        p.Start();
                        sw.WriteLine(i);
                        sw.WriteLine(lim);
                    }
                }
            }
            Console.ReadLine();
        }
コード例 #24
0
ファイル: ProtocolTets.cs プロジェクト: LazyMode/StreamEx
    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');
                }
            }
    }
コード例 #25
0
        static void Main()
        {
            XmlLoader.LoadStrings("wz\\longcoatxmlstr.xml");
            XmlLoader.LoadStrings("wz\\capexmlstr.xml");
            XmlLoader.LoadStrings("wz\\glovexmlstr.xml");
            XmlLoader.LoadStrings("wz\\shoesxmlstr.xml");
            XmlLoader.LoadStrings("wz\\weaponxmlstr.xml");

            SetupPipe();
            var processInfo = new ProcessStartInfo
            {
                FileName         = "..\\Engine\\NxSim.exe",
                Arguments        = pipeServer.GetClientHandleAsString(),
                WorkingDirectory = System.IO.Path.GetDirectoryName("..\\Engine\\NxSim.exe"),
                UseShellExecute  = false
            };

            Console.WriteLine("Starting child process...");
            Process.Start(processInfo);

            //using (var process = Process.Start(processInfo))
            //{
            //process.WaitForExit();
            //}
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new GuiForm());
        }
コード例 #26
0
        /// <summary>
        /// 创建一个AnonymousPipeServerStream,定义PipeDirection.In,把服务器端充当读取器。
        /// 通信的另一端需要知道管道的客户端句柄。这个句柄在GetClientHandleAsString方法中转换为一个字符串,
        /// 赋予_pipeHandele变量。这个变量以后由充当写入器的客户端使用。
        /// 在最初的处理后,管道服务器可以作为一个流,因为它本来就是一个流
        /// </summary>
        private static void Reader()
        {
            try
            {
                var pipeReader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None);
                using (var reader = new StreamReader(pipeReader))
                {
                    _pipeHandle = pipeReader.GetClientHandleAsString();
                    Console.WriteLine($"管道句柄:{_pipeHandle}");
                    _pipeHandleSet.Set();

                    bool end = false;
                    while (!end)
                    {
                        string line = reader.ReadLine();
                        Console.WriteLine(line);
                        if (line == "end")
                        {
                            end = true;
                        }
                    }
                    Console.WriteLine("读取已完成");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #27
0
        /// <summary>
        /// Main task thread for working with a single APSIMRunner.exe process using
        /// an anonymous pipe.
        /// </summary>
        private void PipeServerTaskThread()
        {
            // Create 2 anonymous pipes (read and write) for duplex communications
            // (each pipe is one-way)
            using (var pipeRead = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                using (var pipeWrite = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                {
                    var pipeHandles = pipeRead.GetClientHandleAsString() + " " + pipeWrite.GetClientHandleAsString();

                    // Run a APSIMRunner process passing the pipe read and write handles as arguments.
                    var runnerProcess = new ProcessUtilities.ProcessWithRedirectedOutput();
                    runnerProcess.Exited += OnExited;
                    var runnerExecutable = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "APSIMRunner.exe");
                    runnerProcess.Start(executable: runnerExecutable,
                                        arguments: pipeHandles,
                                        workingDirectory: Directory.GetCurrentDirectory(),
                                        redirectOutput: true,
                                        writeToConsole: false);

                    // Release the local handles that were created with the above GetClientHandleAsString calls
                    pipeRead.DisposeLocalCopyOfClientHandle();
                    pipeWrite.DisposeLocalCopyOfClientHandle();

                    try
                    {
                        // Get the next job to run.
                        var job = GetJobToRun();

                        while (job != null)
                        {
                            var startTime = DateTime.Now;

                            // Send the job to APSIMRunner.exe - this will run the simulation.
                            PipeUtilities.SendObjectToPipe(pipeWrite, job.JobSentToClient);

                            pipeWrite.WaitForPipeDrain();

                            // Get the output data back from APSIMRunner.exe
                            var endJob = PipeUtilities.GetObjectFromPipe(pipeRead) as JobOutput;

                            // Send the output data to storage.
                            endJob.WriteOutput(job.DataStore);

                            // Signal end of job.
                            InvokeJobCompleted(job.RunnableJob,
                                               job.JobManager,
                                               startTime,
                                               endJob.ErrorMessage);

                            // Get the next job to run.
                            job = GetJobToRun();
                        }
                    }
                    catch (Exception err)
                    {
                        AddException(err);
                    }
                }
        }
コード例 #28
0
ファイル: AnonymousPipes.cs プロジェクト: wook8170/EDRAgent
        private String StartPipeServer()
        {
            serverMode         = true;
            outGoingServerPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            inComingServerPipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);

            return(outGoingServerPipe.GetClientHandleAsString() + ":::" + inComingServerPipe.GetClientHandleAsString());
        }
コード例 #29
0
 protected override void BeforeChildStart()
 {
     base.BeforeChildStart();
     childInputPipe    = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable, Program.BUFFER_SIZE);
     childOutputPipe   = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, Program.BUFFER_SIZE);
     childInputHandle  = childInputPipe.GetClientHandleAsString();
     childOutputHandle = childOutputPipe.GetClientHandleAsString();
 }
コード例 #30
0
 public static void CreateClientStreamFromStringHandle_Valid()
 {
     using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
         using (var client = new AnonymousPipeClientStream(server.GetClientHandleAsString()))
         {
             SuppressClientHandleFinalizationIfNetFramework(server);
         }
 }
コード例 #31
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);
                }
            }
        }
コード例 #32
0
        public static void ClonedClient_ActsAsOriginalClient()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                using (AnonymousPipeClientStream clientBase = new AnonymousPipeClientStream(PipeDirection.In, server.GetClientHandleAsString()))
                {
                    using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, clientBase.SafePipeHandle))
                    {
                        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]);
                    }
                }
            }
        }
コード例 #33
0
 public static void CreateClientStreamFromStringHandle_Valid()
 {
     using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
     using (var client = new AnonymousPipeClientStream(server.GetClientHandleAsString()))
     { }
 }
コード例 #34
0
 public void ReadModeToByte_Accepted(PipeDirection serverDirection, PipeDirection clientDirection)
 {
     using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(serverDirection))
     using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(clientDirection, server.GetClientHandleAsString()))
     {
         server.ReadMode = PipeTransmissionMode.Byte;
         client.ReadMode = PipeTransmissionMode.Byte;
         Assert.Equal(PipeTransmissionMode.Byte, server.ReadMode);
         Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode);
     }
 }
コード例 #35
0
 public void MessageReadMode_Throws_NotSupportedException()
 {
     using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
     using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.GetClientHandleAsString()))
     {
         Assert.Throws<NotSupportedException>(() => server.ReadMode = PipeTransmissionMode.Message);
         Assert.Throws<NotSupportedException>(() => client.ReadMode = PipeTransmissionMode.Message);
     }
 }
コード例 #36
0
 public void InvalidReadMode_Throws_ArgumentOutOfRangeException()
 {
     using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
     using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.GetClientHandleAsString()))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);
         Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999);
     }
 }