{"id":10,"date":"2011-08-27T17:22:26","date_gmt":"2011-08-28T00:22:26","guid":{"rendered":"http:\/\/gigglenuts.com\/blog\/?p=10"},"modified":"2011-08-29T16:26:13","modified_gmt":"2011-08-29T23:26:13","slug":"spawning-processes-and-redirecting-io-in-net","status":"publish","type":"post","link":"https:\/\/gigglenuts.com\/blog\/?p=10","title":{"rendered":"Robust Process Spawning and IO Redirection in .NET"},"content":{"rendered":"<p>Many times something seems simple on the surface, but once you start you find it is a pain in the neck. Then, once in awhile, you find it is beyond a pain in the neck. For example, spawning a process and capturing stdout\/stderr in .NET. Sure, it doesn't seem hard, create an instance of the Process class, fill in some members, kick it off and wait until it finishes. Works great! On to the next problem...<\/p>\n<p>Until the day it locks up on you unexpectedly. Hmm.<\/p>\n<p>The next step is then to ask the modern Oracle - Google, to see if others have this problem. Sure enough, you find out that if the child process' buffer becomes full, it blocks, and that is causing your deadlock. Even better, there are tons of helpful people on the Internet willing to share the solution to this problem, along with source code snippets. Score! Asynchronous reads for the win. Hook it up, and on to the next problem...<\/p>\n<p>Until the day it locks up on you unexpectedly. Hmm.<\/p>\n<p>I got to this point, and Google began to fail me. It seems either no one ran into this problem, or, the only solution people talk about is the method I'm already using. We write all our crunching tools using C\/C++ as \u00a0command line tools, and then a GUI in C# that spawns these tools.\u00a0Most of the time, things ran fine for me - but, under heavy stress conditions, such as the child writing a lot of output, the whole thing would lock up. I even had a reproducible case, where it would lock up 100% of the time for a given command line tool with a certain set of arguments. We debugged our hearts out, trying every which way we could to keep things moving on, but we kept coming up short.<\/p>\n<p>I can't say with 100% confidence, only 99%, that the issue was not mine, but Microsoft's. If you try to spawn processes that [may] write to both stdout and stderr (we'll ignore reading from stdin for now), you may find yourself in a world of hurt if one of those buffers fills up. This was a few months ago, and I'm having a hard time remembering the exact details, but it may have been related to the asynchronous call backs for the redirected stdout\/stderr being called on the main thread, and, in my case, I was using threadpools for tasks that spawned the processes. My main thread of my application would wait until it got some sort of event from a worker thread that it was done, or there was an error. But, with Microsoft trying to invoke the callback on the main thread for the IO redirection, it never would call to process the buffer, which left the child process waiting for the buffer to clear, and my application's main thread waiting on the worker thread to finish...deadlock.<\/p>\n<p>All I wanted to do was spawn a process and capture all of its stdout and all of its stderr. I did not have to interact with it via stdin at all. You would think this is a simple request. If I only wanted one or the other, I could have just used\u00a0<span class=\"Apple-style-span\" style=\"font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;\">p.StandardOutput.ReadToEnd(); <\/span>and just executed the process synchronously. You do not have that luxury if you want both stdout and stderr - you must use\u00a0asynchronous\u00a0reads, with the callbacks coming only on the main thread. Throw my need for threadpools into the mix and you find things don't work out so well.<\/p>\n<p>All is not lost, I found a solution. The solution is to not use System.Diagnostics.Process and use raw Win32 API to get the same results. I could of \u00a0just wrote a C\/C++ DLL, or a C++\/CLI assembly, but I hate having a mess of DLLs laying around. I wanted a solution that stayed in C#, and so P\/Invoke to the rescue. First I got it all working using straight C\/C++ and then moved it all to C# using P\/Invoke calls to the Win32 API. I'll save you the work, you can find it here:<\/p>\n<pre lang=\"csharp\" line=\"1\">\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace ProcessAPI\r\n{\r\n    #region WIN32 API\r\n    class Win32\r\n    {\r\n        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\r\n        public struct SECURITY_ATTRIBUTES\r\n        {\r\n            public Int32 nLength;\r\n            public IntPtr lpSecurityDescriptor;\r\n            public bool bInheritHandle;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\r\n        public struct STARTUPINFO\r\n        {\r\n            public Int32 cb;\r\n            public string lpReserved;\r\n            public string lpDesktop;\r\n            public string lpTitle;\r\n            public Int32 dwX;\r\n            public Int32 dwY;\r\n            public Int32 dwXSize;\r\n            public Int32 dwYSize;\r\n            public Int32 dwXCountChars;\r\n            public Int32 dwYCountChars;\r\n            public Int32 dwFillAttribute;\r\n            public Int32 dwFlags;\r\n            public Int16 wShowWindow;\r\n            public Int16 cbReserved2;\r\n            public IntPtr lpReserved2;\r\n            public IntPtr hStdInput;\r\n            public IntPtr hStdOutput;\r\n            public IntPtr hStdError;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\r\n        public struct PROCESS_INFORMATION\r\n        {\r\n            public IntPtr hProcess;\r\n            public IntPtr hThread;\r\n            public Int32 dwProcessId;\r\n            public Int32 dwThreadId;\r\n        }\r\n\r\n        [Flags]\r\n        public enum DuplicateOptions : uint\r\n        {\r\n            DUPLICATE_CLOSE_SOURCE = (0x00000001),\/\/ Closes the source handle. This occurs regardless of any error status returned.\r\n            DUPLICATE_SAME_ACCESS = (0x00000002), \/\/Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.\r\n        }\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern Boolean CreatePipe(\r\n            out IntPtr hReadPipe,\r\n            out IntPtr hWritePipe,\r\n            ref SECURITY_ATTRIBUTES lpPipeAttributes,\r\n            uint nSize);\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern IntPtr GetCurrentProcess();\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        [return: MarshalAs(UnmanagedType.Bool)]\r\n        public static extern Boolean DuplicateHandle(\r\n            IntPtr hSourceProcessHandle,\r\n            IntPtr hSourceHandle,\r\n            IntPtr hTargetProcessHandle,\r\n            out IntPtr lpTargetHandle,\r\n            UInt32 dwDesiredAccess,\r\n            [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,\r\n            UInt32 dwOptions);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]\r\n        public static extern IntPtr CreateEvent(IntPtr lpEventAttributes,\r\n            [In, MarshalAs(UnmanagedType.Bool)] Boolean bManualReset,\r\n            [In, MarshalAs(UnmanagedType.Bool)] Boolean bIntialState,\r\n            [In, MarshalAs(UnmanagedType.BStr)] string lpName);\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern void SetLastError(Int32 dwErrCode);\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern bool SetEvent(IntPtr hEvent);\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern Boolean WriteFile(\r\n            IntPtr hFile,\r\n            Byte[] lpBuffer,\r\n            UInt32 nNumberOfBytesToWrite,\r\n            out UInt32 lpNumberOfBytesWritten,\r\n            IntPtr lpOverlapped);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        public static extern bool ReadFile(\r\n            IntPtr hFile,\r\n            [Out] Byte[] lpBuffer,\r\n            UInt32 nNumberOfBytesToRead,\r\n            out UInt32 lpNumberOfBytesRead,\r\n            IntPtr lpOverlapped);\r\n\r\n        [DllImport(\"kernel32.dll\")]\r\n        public static extern bool CreateProcess(\r\n            string lpApplicationName,\r\n            string lpCommandLine,\r\n            IntPtr lpProcessAttributes,\r\n            IntPtr lpThreadAttributes,\r\n            Boolean bInheritHandles,\r\n            UInt32 dwCreationFlags,\r\n            IntPtr lpEnvironment,\r\n            string lpCurrentDirectory,\r\n            [In] ref STARTUPINFO lpStartupInfo,\r\n            out PROCESS_INFORMATION lpProcessInformation);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        [return: MarshalAs(UnmanagedType.Bool)]\r\n        public static extern bool TerminateProcess(IntPtr hProcess, UInt32 uExitCode);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]\r\n        [return: MarshalAs(UnmanagedType.Bool)]\r\n        public static extern bool CloseHandle(IntPtr hObject);\r\n\r\n        [DllImport(\"kernel32.dll\", EntryPoint = \"PeekNamedPipe\", SetLastError = true)]\r\n        public static extern bool PeekNamedPipe(\r\n            IntPtr handle,\r\n            Byte[] buffer,\r\n            UInt32 nBufferSize,\r\n            ref UInt32 bytesRead,\r\n            ref UInt32 bytesAvail,\r\n            ref UInt32 BytesLeftThisMessage);\r\n\r\n        [DllImport(\"kernel32.dll\", EntryPoint = \"WaitForMultipleObjects\", SetLastError = true)]\r\n        public static extern int WaitForMultipleObjects(\r\n            UInt32 nCount,\r\n            IntPtr[] lpHandles,\r\n            Boolean fWaitAll,\r\n            UInt32 dwMilliseconds);\r\n\r\n        [DllImport(\"kernel32.dll\", SetLastError = true)]\r\n        [return: MarshalAs(UnmanagedType.Bool)]\r\n        public static extern Boolean GetExitCodeProcess(IntPtr hProcess, out Int32 lpExitCode);\r\n    }\r\n    #endregion\r\n\r\n    public class ProcessRedirector : IDisposable\r\n    {\r\n        #region Internal Members\r\n        private System.Threading.Thread m_hThread; \/\/ thread to receive the output of the child process\r\n        private IntPtr m_hEvtStop; \/\/ event to notify the redir thread to exit\r\n        private Int32 m_dwThreadId; \/\/ id of the redir thread\r\n        private Int32 m_resultCode; \/\/ returned result code of the process\r\n        private UInt32 m_dwWaitTime; \/\/ wait time to check the status of the child process\r\n\r\n        protected IntPtr m_hStdinWrite; \/\/ write end of child's stdin pipe\r\n        protected IntPtr m_hStdoutRead; \/\/ read end of child's stdout pipe\r\n        protected IntPtr m_hStderrRead; \/\/ read end of child's stderr pipe\r\n        protected IntPtr m_hChildProcess;\r\n        #endregion\r\n\r\n        #region Constructor\r\n        public ProcessRedirector()\r\n        {\r\n            m_hStdinWrite = IntPtr.Zero;\r\n            m_hStdoutRead = IntPtr.Zero;\r\n            m_hStderrRead = IntPtr.Zero;\r\n            m_hChildProcess = IntPtr.Zero;\r\n            m_hThread = null;\r\n            m_hEvtStop = IntPtr.Zero;\r\n            m_dwThreadId = 0;\r\n            m_dwWaitTime = 100;\r\n            m_resultCode = -1;\r\n        }\r\n        #endregion\r\n\r\n        #region Finalizer\r\n        \/\/ NOTE: Leave out the finalizer altogether if this class doesn't \r\n        \/\/ own unmanaged resources itself, but leave the other methods\r\n        \/\/ exactly as they are. \r\n        ~ProcessRedirector()\r\n        {\r\n            \/\/ Finalizer calls Dispose(false)\r\n            Dispose(false);\r\n        }\r\n        #endregion\r\n\r\n        #region Dispose\r\n        public void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        \/\/ The bulk of the clean-up code is implemented in Dispose(bool)\r\n        protected virtual void Dispose(bool disposing)\r\n        {\r\n            if (disposing)\r\n            {\r\n                \/\/ free managed resources\r\n            }\r\n\r\n            \/\/ free native resources if there are any.\r\n            Close(true);\r\n        }\r\n        #endregion\r\n\r\n        #region Property: ResultCode\r\n        \/\/\/ <summary>\r\n        \/\/\/ Access the return code from the spawned process\r\n        \/\/\/ <\/summary>\r\n        public Int32 ResultCode\r\n        {\r\n            get { return m_resultCode; }\r\n        }\r\n        #endregion\r\n\r\n        #region protected LaunchChild\r\n        protected bool LaunchChild(string pathToApp, string workingDirectory, string args, IntPtr hStdOut, IntPtr hStdIn, IntPtr hStdErr)\r\n        {\r\n            const Int16 SW_HIDE = 0;\r\n            const Int32 STARTF_USESTDHANDLES = 0x100;\r\n            const Int32 STARTF_USESHOWWINDOW = 0x1;\r\n            const uint CREATE_NEW_CONSOLE = 0x00000010;\r\n\r\n            \/\/ Set up the start up info struct.\r\n            Win32.STARTUPINFO si = new Win32.STARTUPINFO();\r\n            si.cb = Marshal.SizeOf(si);\r\n            si.hStdOutput = hStdOut;\r\n            si.hStdInput = hStdIn;\r\n            si.hStdError = hStdErr;\r\n            si.wShowWindow = SW_HIDE;\r\n            si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\r\n\r\n            \/\/ Note that dwFlags must include STARTF_USESHOWWINDOW if we\r\n            \/\/ use the wShowWindow flags. This also assumes that the\r\n            \/\/ CreateProcess() call will use CREATE_NEW_CONSOLE.\r\n            Win32.PROCESS_INFORMATION pi = new Win32.PROCESS_INFORMATION();\r\n\r\n            \/\/ Launch the child process.\r\n            if (!Win32.CreateProcess(pathToApp, args, IntPtr.Zero, IntPtr.Zero, true, CREATE_NEW_CONSOLE, IntPtr.Zero, workingDirectory, ref si, out pi))\r\n                return false;\r\n\r\n            m_hChildProcess = pi.hProcess;\r\n\r\n            \/\/ Close any non-useful handles\r\n            Win32.CloseHandle(pi.hThread);\r\n            return true;\r\n        }\r\n        #endregion\r\n\r\n        #region protected DestroyHandle\r\n        protected void DestroyHandle(ref IntPtr rhObject)\r\n        {\r\n            if (rhObject == IntPtr.Zero)\r\n                return;\r\n\r\n            Win32.CloseHandle(rhObject);\r\n            rhObject = IntPtr.Zero;\r\n        }\r\n        #endregion\r\n\r\n        #region private InternalClose\r\n        private void InternalClose(bool getExitCode)\r\n        {\r\n            if (getExitCode && m_hChildProcess != IntPtr.Zero)\r\n            {\r\n                \/\/ Snag the exit code before it's gone\r\n                if (!Win32.GetExitCodeProcess(m_hChildProcess, out m_resultCode))\r\n                {\r\n                    m_resultCode = -1;\r\n                }\r\n            }\r\n\r\n            DestroyHandle(ref m_hEvtStop);\r\n            DestroyHandle(ref m_hChildProcess);\r\n            DestroyHandle(ref m_hStdinWrite);\r\n            DestroyHandle(ref m_hStdoutRead);\r\n            DestroyHandle(ref m_hStderrRead);\r\n            m_dwThreadId = 0;\r\n        }\r\n        #endregion\r\n\r\n        #region Stdout\/Stderr redirection processing\r\n        delegate void RedirectDelegate(string msg);\r\n        int InternalRedirect(IntPtr hPipeRead, RedirectDelegate del)\r\n        {\r\n            const int ERROR_BROKEN_PIPE = 109;\r\n            const int ERROR_NO_DATA = 232;\r\n\r\n            for (; ; )\r\n            {\r\n                uint bytesRead = 0;\r\n                uint dwAvail = 0;\r\n                uint bytesLeft = 0;\r\n                if (!Win32.PeekNamedPipe(hPipeRead, null, 0, ref bytesRead, ref dwAvail, ref bytesLeft))\r\n                    break; \/\/ error\r\n\r\n                if (dwAvail == 0)\r\n                {\r\n                    \/\/ no data available\r\n                    return 1;\r\n                }\r\n\r\n                byte[] szOutput = new byte[dwAvail];\r\n                if (!Win32.ReadFile(hPipeRead, szOutput, dwAvail, out bytesRead, IntPtr.Zero) || bytesRead == 0)\r\n                    break; \/\/ error, the child might have ended\r\n\r\n                del(ASCIIEncoding.ASCII.GetString(szOutput, 0, (int)bytesRead));\r\n            }\r\n\r\n            int dwError = Marshal.GetLastWin32Error();\r\n            if (dwError == ERROR_BROKEN_PIPE ||\t\/\/ pipe has been ended\r\n                dwError == ERROR_NO_DATA)\t\t\/\/ pipe closing in progress\r\n            {\r\n                return 0;\t\/\/ child process ended\r\n            }\r\n\r\n            WriteStdError(\"Read stdout pipe error\\r\\n\");\r\n            return -1;\t\t\/\/ os error\r\n        }\r\n\r\n        \/\/ redirect the child process's stdout:\r\n        \/\/ return: 1: no more data, 0: child terminated, -1: os error\r\n        protected int RedirectStdout()\r\n        {\r\n            return InternalRedirect(m_hStdoutRead, new RedirectDelegate(delegate(string msg) { WriteStdOut(msg); }));\r\n        }\r\n\r\n        \/\/ redirect the child process's stderr:\r\n        \/\/ return: 1: no more data, 0: child terminated, -1: os error\r\n        protected int RedirectStderr()\r\n        {\r\n            return InternalRedirect(m_hStderrRead, new RedirectDelegate(delegate(string msg) { WriteStdError(msg); }));\r\n        }\r\n\r\n        protected void OutputThread()\r\n        {\r\n            const int WAIT_OBJECT_0 = 0;\r\n\r\n            IntPtr[] aHandles = new IntPtr[2];\r\n            aHandles[0] = m_hChildProcess;\r\n            aHandles[1] = m_hEvtStop;\r\n\r\n            bool exitNormally = false;\r\n            for (; ; )\r\n            {\r\n                \/\/ redirect stdout till there's no more data.\r\n                int nRet;\r\n\r\n                nRet = RedirectStdout();\r\n                if (nRet < 0)\r\n                    break;\r\n\r\n                nRet = RedirectStderr();\r\n                if (nRet < 0)\r\n                    break;\r\n\r\n                \/\/ check if the child process has terminated.\r\n                int dwRc = Win32.WaitForMultipleObjects(2, aHandles, false, m_dwWaitTime);\r\n                if (WAIT_OBJECT_0 == dwRc)\t\t\/\/ the child process ended\r\n                {\r\n                    RedirectStdout();\r\n                    RedirectStderr();\r\n                    exitNormally = true;\r\n                    break;\r\n                }\r\n\r\n                if (WAIT_OBJECT_0 + 1 == dwRc)\t\/\/ m_hEvtStop was signalled\r\n                {\r\n                    Win32.TerminateProcess(m_hChildProcess, 0xFFFFFFFF);\r\n                    break;\r\n                }\r\n            }\r\n\r\n            \/\/ close handles\r\n            InternalClose(exitNormally);\r\n        }\r\n        #endregion\r\n\r\n        #region virtual WriteStdOut\r\n        \/\/\/ <summary>\r\n        \/\/\/ Override to handle processing data written to stdout by the process\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"outputStr\"><\/param>\r\n        protected virtual void WriteStdOut(string outputStr)\r\n        {\r\n            Console.Out.Write(outputStr);\r\n        }\r\n        #endregion\r\n\r\n        #region virtual WriteStdError\r\n        \/\/\/ <summary>\r\n        \/\/\/ Override to handle processing data written to stderr by the process\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"errorStr\"><\/param>\r\n        protected virtual void WriteStdError(string errorStr)\r\n        {\r\n            Console.Error.Write(errorStr);\r\n        }\r\n        #endregion\r\n\r\n        #region Open\r\n        \/\/\/ <summary>\r\n        \/\/\/ Initialize and spawn a process\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"pathToApp\">Absolute path to the executable to spawn<\/param>\r\n        \/\/\/ <param name=\"workingDirectory\">The working directory for the process<\/param>\r\n        \/\/\/ <param name=\"args\">The full set of command line arguments<\/param>\r\n        \/\/\/ <returns>True if everything went okay<\/returns>\r\n        public bool Open(string pathToApp, string workingDirectory, string args)\r\n        {\r\n            Close(true);\r\n\r\n            IntPtr hStdoutReadTmp = IntPtr.Zero; \/\/ parent stdout read handle\r\n            IntPtr hStderrReadTmp = IntPtr.Zero; \/\/ parent stderr read handle\r\n            IntPtr hStdoutWrite = IntPtr.Zero; \/\/ child stdout write handle\r\n            IntPtr hStderrWrite = IntPtr.Zero;\r\n            IntPtr hStdinWriteTmp = IntPtr.Zero; \/\/ parent stdin write handle\r\n            IntPtr hStdinRead = IntPtr.Zero; \/\/ child stdin read handle\r\n\r\n            \/\/ Set up the security attributes struct.\r\n            Win32.SECURITY_ATTRIBUTES sa = new Win32.SECURITY_ATTRIBUTES();\r\n            sa.nLength = Marshal.SizeOf(sa);\r\n            sa.lpSecurityDescriptor = IntPtr.Zero;\r\n            sa.bInheritHandle = true;\r\n            m_resultCode = -1;\r\n\r\n            bool setupOk = false;\r\n            try\r\n            {\r\n                \/\/ Create a child stdout pipe.\r\n                if (!Win32.CreatePipe(out hStdoutReadTmp, out hStdoutWrite, ref sa, 0))\r\n                    return false;\r\n\r\n                \/\/ Create a child stderr pipe.\r\n                if (!Win32.CreatePipe(out hStderrReadTmp, out hStderrWrite, ref sa, 0))\r\n                    return false;\r\n\r\n                \/\/ Create a child stdin pipe.\r\n                if (!Win32.CreatePipe(out hStdinRead, out hStdinWriteTmp, ref sa, 0))\r\n                    return false;\r\n\r\n                \/\/ Create new stdout read handle, stderr read handle and the stdin write handle.\r\n                \/\/ Set the inheritance properties to FALSE. Otherwise, the child\r\n                \/\/ inherits the these handles; resulting in non-closeable\r\n                \/\/ handles to the pipes being created.\r\n                if (!Win32.DuplicateHandle(Win32.GetCurrentProcess(), hStdoutReadTmp, Win32.GetCurrentProcess(), out m_hStdoutRead, 0, false, (uint)Win32.DuplicateOptions.DUPLICATE_SAME_ACCESS))\r\n                    return false;\r\n\r\n                if (!Win32.DuplicateHandle(Win32.GetCurrentProcess(), hStderrReadTmp, Win32.GetCurrentProcess(), out m_hStderrRead, 0, false, (uint)Win32.DuplicateOptions.DUPLICATE_SAME_ACCESS))\r\n                    return false;\r\n\r\n                if (!Win32.DuplicateHandle(Win32.GetCurrentProcess(), hStdinWriteTmp, Win32.GetCurrentProcess(), out m_hStdinWrite, 0, false, (uint)Win32.DuplicateOptions.DUPLICATE_SAME_ACCESS))\r\n                    return false;\r\n\r\n                \/\/ Close inheritable copies of the handles we do not want to be inherited.\r\n                DestroyHandle(ref hStdoutReadTmp);\r\n                DestroyHandle(ref hStderrReadTmp);\r\n                DestroyHandle(ref hStdinWriteTmp);\r\n\r\n                \/\/ launch the child process\r\n                string appFilename = System.IO.Path.GetFileName(pathToApp);\r\n                string cmdArgs = \"\\\"\" + appFilename + \"\\\" \" + args;\r\n                if (!LaunchChild(pathToApp, workingDirectory, cmdArgs, hStdoutWrite, hStdinRead, hStderrWrite))\r\n                    return false;\r\n\r\n                \/\/ Child is launched. Close the parents copy of those pipe\r\n                \/\/ handles that only the child should have open.\r\n                \/\/ Make sure that no handles to the write end of the stdout pipe\r\n                \/\/ are maintained in this process or else the pipe will not\r\n                \/\/ close when the child process exits and ReadFile will hang.\r\n                DestroyHandle(ref hStdoutWrite);\r\n                DestroyHandle(ref hStdinRead);\r\n                DestroyHandle(ref hStderrWrite);\r\n\r\n                \/\/ Launch a thread to receive output from the child process.\r\n                m_hEvtStop = Win32.CreateEvent(IntPtr.Zero, true, false, null);\r\n\r\n                try\r\n                {\r\n                    m_hThread = new System.Threading.Thread(new System.Threading.ThreadStart(OutputThread));\r\n                    m_hThread.Name = \"StdOutErr Processor \" + appFilename;\r\n                }\r\n                catch\r\n                {\r\n                    return false;\r\n                }\r\n                m_hThread.Start();\r\n                m_dwThreadId = m_hThread.ManagedThreadId;\r\n                setupOk = true;\r\n            }\r\n            finally\r\n            {\r\n                if (!setupOk)\r\n                {\r\n                    Int32 dwOsErr = Marshal.GetLastWin32Error();\r\n                    if (dwOsErr != 0)\r\n                    {\r\n                        WriteStdError(\"Redirect console error: \" + dwOsErr.ToString(\"x8\") + \"\\r\\n\");\r\n                    }\r\n\r\n                    DestroyHandle(ref hStdoutReadTmp);\r\n                    DestroyHandle(ref hStderrReadTmp);\r\n                    DestroyHandle(ref hStdoutWrite);\r\n                    DestroyHandle(ref hStderrWrite);\r\n                    DestroyHandle(ref hStdinWriteTmp);\r\n                    DestroyHandle(ref hStdinRead);\r\n                    Close(true);\r\n\r\n                    Win32.SetLastError(dwOsErr);\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n        #endregion\r\n\r\n        #region Close\r\n        \/\/\/ <summary>\r\n        \/\/\/ Close a process\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"abort\">If true, abort the processing (waiting up to\r\n        \/\/\/ 5 seconds before terminating), otherwise just wait until it exits<\/param>\r\n        public virtual void Close(bool abort)\r\n        {\r\n            if (m_hThread != null)\r\n            {\r\n                if (abort)\r\n                {\r\n                    \/\/ tell the thread to bail\r\n                    Win32.SetEvent(m_hEvtStop);\r\n                    if (!m_hThread.Join(5000))\r\n                    {\r\n                        try\r\n                        {\r\n                            m_hThread.Abort();\r\n                        }\r\n                        catch\r\n                        {\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    \/\/ wait until the thread exits\r\n                    m_hThread.Join();\r\n                }\r\n\r\n                m_hThread = null;\r\n            }\r\n\r\n            InternalClose(false);\r\n        }\r\n        #endregion\r\n\r\n        #region SendToStdIn\r\n        \/\/\/ <summary>\r\n        \/\/\/ Send the given string of data to the stdin of the spawned process\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"str\"><\/param>\r\n        \/\/\/ <returns><\/returns>\r\n        public bool SendToStdIn(string str)\r\n        {\r\n            if (m_hStdinWrite == IntPtr.Zero)\r\n                return false;\r\n\r\n            byte[] strData = ASCIIEncoding.ASCII.GetBytes(str);\r\n\r\n            uint dwWritten;\r\n            return Win32.WriteFile(m_hStdinWrite, strData, (uint)strData.Length, out dwWritten, IntPtr.Zero);\r\n        }\r\n        #endregion\r\n\r\n        #region SetWaitTime\r\n        \/\/\/ <summary>\r\n        \/\/\/ Adjust the waiting time between checks to see if the process\r\n        \/\/\/ has exited, this is also the time between checks to stdout and\r\n        \/\/\/ stderr processing.\r\n        \/\/\/ <\/summary>\r\n        \/\/\/ <param name=\"waitTime\"><\/param>\r\n        public void SetWaitTime(UInt32 waitTime)\r\n        {\r\n            m_dwWaitTime = waitTime;\r\n        }\r\n        #endregion\r\n    }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Many times something seems simple on the surface, but once you start you find it is a pain in the neck. Then, once in awhile, you find it is beyond a pain in the neck. For example, spawning a process and capturing stdout\/stderr in .NET. Sure, it doesn&#8217;t seem hard, create an instance of the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/10"}],"collection":[{"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10"}],"version-history":[{"count":8,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/10\/revisions"}],"predecessor-version":[{"id":18,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/10\/revisions\/18"}],"wp:attachment":[{"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gigglenuts.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}