Process.HasExited returns true even though process is running?

36,184

Solution 1

I realize this is an old post, but in my quest to find out why my app running the Exited event before the app had even opened I found out something that I though might be useful to people experiencing this problem in the future.

When a process is started, it is assigned a PID. If the User is then prompted with the User Account Control dialog and selects 'Yes', the process is re-started and assigned a new PID.

I sat with this for a few hours, hopefully this can save someone time.

Solution 2

I would suggest you to try this way:

process.Start();

while (!process.HasExited)
{
    // Discard cached information about the process.
    process.Refresh();

    // Just a little check!
    Console.WriteLine("Physical Memory Usage: " + process.WorkingSet64.ToString());

    Thread.Sleep(500);
}

foreach (Process current in Process.GetProcessesByName("testprogram"))
{
    if ((current.Id == process.Id) && !current.HasExited)
        throw new Exception("Oh oh!");
}

Anyway... in MSDN page of HasExited I'm reading the following hightlighted note:

When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this property returns true. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter before checking HasExited.

That could be somehow linked to your problem as you are redirecting everything.

Solution 3

I know, this is an old post but maybe I can help someone.
The Process class may behave unexpectedly. HasExited will return true if the process has exited or if the process runs with administrator privileges and your program only has user privileges.

I have posted a question regarding this a while back here, but did not receive a satisfiable answer.

Solution 4

First off, are you sure testprogram does not spawn a process of its own and exit without waiting for that process to finish? We're dealing with some kind of race condition here, and testprogram can be significant.

Second point I'd like to make is about this - "I need to be absolutely sure that this logfile exists". Well, there is no such thing. You can make your check, and then the file is gone. The common way to address this is not to check, but rather to do what you want to do with the file. Go ahead, read it, catch exceptions, retry if the thing seems unstable and you don't want to change anything. The functional check-and-do does not work well if you have more than one actor (thread or whatever) in the system.

A bunch of random ideas follows.

Have you tried using FileSystemWatcher and not depending on process completion?

Does it get any better if you try reading the file (not checking if it exists, but acting instead) in the process.Exited event? [it shouldn't]

Is the system healthy? Anything suspicious in the Event Log?

Can some really aggressive antivirus policy be involved?

(Can't tell much without seeing all the code and looking into testprogram.)

Solution 5

So just for a further investigation into the root cause of the problem you should maybe check out what's really happening by using Process Monitor. Simply start it and include the external program and your own tool and let it record what happens.

Within the log you should see how the external tool writes to the output file and how you open that file. But within this log you should see in which order all these accesses happen.

The first thing that came to my mind is that the Process class doesn't lie and the process is really gone when it tells so. So problem is that at this point in time it seems that the file is still not fully available. I think this is a problem of the OS, cause it holds some parts of the file still within a cache that is not fully written onto the disk and the tool has simply exited itself without flushing its file handles.

With this in mind you should see within the log that the external tool created the file, exited and AFTER that the file will be flushed/closed (by the OS [maybe remove any filters when you found this point within the log]).

So if my assumptions are correct the root cause would be the bad behavior of your external tool which you can't change thus leading to simply wait a little bit after the process has exited and hope that the timeout is long enough to get the file flushed/closed by the OS (maybe try to open the file in a loop with a timeout till it succeeded).

Share:
36,184
johnrl
Author by

johnrl

Updated on January 06, 2022

Comments

  • johnrl
    johnrl over 2 years

    I have been observing that Process.HasExited sometimes returns true even though the process is still running.

    My code below starts a process with name "testprogram.exe" and then waits for it to exit. The problem is that sometimes I get thrown the exception; it seems that even though HasExited returns true the process itself is still alive in the system - how can this be??

    My program writes to a log file just before it terminates and thus I need to be absolutely sure that this log file exists (aka the process has terminated/finished) before reading it. Continuously checking for it's existence is not an option.

    // Create new process object
    process = new Process();
    
    // Setup event handlers
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += OutputDataReceivedEvent;
    process.ErrorDataReceived += ErrorDataReceivedEvent;
    process.Exited += ProgramExitedEvent;
    
    // Setup start info
    ProcessStartInfo psi = new ProcessStartInfo
                               {
                                   FileName = ExePath,
                                   // Must be false to redirect IO
                                   UseShellExecute = false,
                                   RedirectStandardOutput = true,
                                   RedirectStandardError = true,
                                   Arguments = arguments
                               };
    
    process.StartInfo = psi;
    
    // Start the program
    process.Start();
    
    while (!process.HasExited)
        Thread.Sleep( 500 );
    
    Process[] p = Process.GetProcessesByName( "testprogram" );
    
    if ( p.Length != 0 )
        throw new Exception("Oh oh");
    

    UPDATE: I just tried waiting with process.WaitForExit() instead of the polling loop and the result is the exact same.

    Addition: The above code was only to demonstrate a 'clearer' problem alike. To make it clear; my problem is NOT that I still can get a hold of the process by Process.GetProcessesByName( "testprogram" ); after it set HasExited to true.

    The real problem is that the program I am running externally writes a file -just before- it terminates (gracefully). I use HasExited to check when the process has finished and thus I know I can read the file (because the process exited!), but it seems that HasExited returns true even sometimes when the program has NOT written the file to disk yet. Here's example code that illustrates the exact problem:

    // Start the program
    process.Start();
    
    while (!process.HasExited)
        Thread.Sleep( 500 );
    // Could also be process.WaitForExit(), makes no difference to the result
    
    // Now the process has quit, I can read the file it has exported
    if ( !File.Exists( xmlFile ) )
    {
        // But this exception is thrown occasionally, why?
        throw new Exception("xml file not found");
    }