How to run child process in the same console in C#


facebooktwittergoogle_pluslinkedinmail

I often hear questions about running sub-process in parent’s console. People got confused about how to make sure that the child process uses the same console as the parent.

Sometimes they try to redirect standard output just to dump it to console via Console.Write. That’s a lot of effort that is not needed if the only thing required is using the same console – not checking the output.

The right way to run child process in the parent’s console is to setup UseShellExecute property of ProcessStartInfo class. Let’s consider an example that executes time command. Why time? Because it reads from standard input. This way you will know which console it uses.

using System;
using System.Diagnostics;

namespace ChildProcessInTheSameConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var processInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = "/c time"
            };

            Console.WriteLine("Starting child process...");
            using (var process = Process.Start(processInfo))
            {
                process.WaitForExit();
            }
        }
    }
}

You can see that the child process is opening a new console.

Child-process-in-new-console

This is not what we wanted. We left the default value of UseShellExecute, which is true. It means that a shell will be used for the child process. Using shell means that a new console will be created.

Let’s flip the value of UseShellExecute to false.

using System;
using System.Diagnostics;

namespace ChildProcessInTheSameConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var processInfo = new ProcessStartInfo
            {
                UseShellExecute = false, // change value to false
                FileName = "cmd.exe",
                Arguments = "/c time"
            };

            Console.WriteLine("Starting child process...");
            using (var process = Process.Start(processInfo))
            {
                process.WaitForExit();
            }
        }
    }
}

This time only one console is used.

Child-process-in-parents-console

That’s all that is needed to redirect all input/output streams to parent’s console.

Advantages of using shell for child processes

There are  some benefits of using shell execute. You can start any document that has open action registered for its file type. For example you can start a text document and a notepad will be opened. But you have to remember that input/output streams won’t be redirected to parents console this way.

 

facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *