Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git diff gets stuck when run as .NET Process

Tags:

git

c#

.net

Running a Git diff gets stuck, till killed when running as a System.Diagnostics.Process.

Code:

class Program
    {
        static void Main(string[] args)
        {
            ProcessStartInfo pInfo = new ProcessStartInfo();
            pInfo.FileName = "git.exe";
            pInfo.Arguments = "diff --name-only --exit-code V2.4-Beta-01 HEAD";
            pInfo.WorkingDirectory = @"C:\Git";
            pInfo.UseShellExecute = false;
            pInfo.CreateNoWindow = true;
            pInfo.RedirectStandardError = true;
            pInfo.RedirectStandardOutput = true;

            Process p = new Process();
            p.StartInfo = pInfo;

            p.Start();

            p.WaitForExit(10000);

            if (!p.HasExited)
            {
                p.Kill();
                Console.WriteLine("Killed!!!");
            }

            Console.WriteLine(p.StandardOutput.ReadToEnd());
            Console.WriteLine(p.StandardError.ReadToEnd());
            Console.ReadLine();
        }
    }

How to avoid this and make the program exists normally without expiring its timeout?

like image 303
Luis Avatar asked Sep 18 '26 02:09

Luis


1 Answers

The problem is that someone has to consume the stdout buffer or it will get filled and the process gets stucked (see explanation here). The diff I was trying retrieved 983 lines, which was causing a buffer overflow.

The following is a solution to my problem:

class Program
    {
        static void Main(string[] args)
        {
            ProcessStartInfo pInfo = new ProcessStartInfo();
            pInfo.FileName = "git.exe";
            pInfo.Arguments = "diff --name-only --exit-code V2.4-Beta-01 HEAD";
            pInfo.WorkingDirectory = @"C:\Git";
            pInfo.UseShellExecute = false;
            pInfo.CreateNoWindow = true;
            pInfo.RedirectStandardError = true;
            pInfo.RedirectStandardOutput = true;

            string output = string.Empty;

            Process p = new Process();
            p.StartInfo = pInfo;

            p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    output += e.Data + Environment.NewLine;
                }
            });

            p.Start();

            p.BeginOutputReadLine();

            p.WaitForExit();
            p.Close();

            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
like image 125
Luis Avatar answered Sep 20 '26 18:09

Luis