Launching a Process in .NET & redirecting the StandardOutput to a LogFile for future Analysis…

Here is a code snippet that I had used a while ago to identify and kill a process that used to hang during the middle of the night.This shows how to Launch a Process, redirect the output to a Log file instead.

The intention was to capture the open handles and kill the process so that the next scheduled run could resume. The Agent that was causing this issue used files for exclusive locks. I suspected an open file might be the cause of the hang. The randomness of the event made it difficult to debug this issue real time in production.

There are other pieces to the Windows Service that are not listed here. Some aspects of the code explained below…

APP_NAME : Name of the Application in uppercase, that I was looking for as displayed in Task Manager.

Logger : Enterprise Library Logging Framework

handle64.exe : downloaded from SysInternals Suite and made available in a folder accessible in the Path Env variable

Arguments to the handle64.exe is to suppress the EULA if and when it appears.

Dim prc() As Process = Process.GetProcesses

For Each p In prc
                If p.ProcessName.ToUpper = APP_NAME Then

                        Dim newP As New Process

                        Logger.Write(String.Format("Terminating Process / Process ID {0}", p.Id))
                        newP.StartInfo.FileName = "handle64.exe"
                        newP.StartInfo.WorkingDirectory = "c:\temp\"
                        newP.StartInfo.RedirectStandardOutput = True
                        newP.StartInfo.UseShellExecute = False
                        newP.StartInfo.Arguments = String.Format("-p {0} -accepteula", p.Id)
                        newP.Start()
                        Dim output As String = newP.StandardOutput.ReadToEnd
                        Logger.Write(output)
                        newP.WaitForExit()

                        p.Kill()
                End If
                p.Dispose()
Next

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: