Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ExitCode of a running process

I'm writing an application to check the exit code of another application. The application I am monitoring may already be running so I'm checking for it with Process.GetProcessesByName. If it exists I'm checking the exit code after a call to WaitForExit but when I do I get an exception:

"Process was not started by this object, so requested information cannot be determined."

If I start the process (if it isn't already running) then it doesn't give me the exception.

(Windows 8.1)

So how do I find out what the ExitCode was when I haven't started the process? The only option I can think of is to write an output code to a text file on exit and read that in...

like image 538
Sean Avatar asked Sep 22 '14 05:09

Sean


1 Answers

System.Diagnostics.Process exposes events that you can access after setting EnableRaisingEvents to true:

    int processId = 0; // TODO: populate this variable
    var proc = System.Diagnostics.Process.GetProcessById(processId);
    proc.EnableRaisingEvents = true;
    proc.Exited += ProcessEnded;

Event handler:

    private void ProcessEnded(object sender, EventArgs e)
    {
        var process = sender as Process;
        if (process != null)
        {
            var test = process.ExitCode;
        }
    }

variable test now contains the exit code.

Tested on Windows 8.1

like image 122
Amadeusz Wieczorek Avatar answered Sep 21 '22 06:09

Amadeusz Wieczorek