WaitForExit() throws exception c# - c#

Below is my code to start the process, have put link for demo only.I want this process to run in background without opening browser. Also 2nd line throws exception
Object reference not set to an instance of an object.
var process=Process.Start("http://www.google.com");
process.WaitForExit();

Because when you start a process indirectly you won't get Process object (then in your case process is always null and second line throws an exception).
Let me explain what I mean with indirectly: if you don't specify an executable but you give a document (or a resource) then it'll be executed through a shell verb. In this case an existing process may be (re)used. In this cases Process.Start() will return null.
Try this:
Create an empty Word document 'c:\test.docx'.
Close all Word instances.
Execute Process.Start(#"c:\test.docx"); // Returns a Process instance
Execute Process.Start(#"c:\test.docx"); // Returns null
Can you simply solve this? AFAIK you can't because Process uses ShellExecuteEx with a SHELLEXECUTEINFO structure to start the process. Reading SHELLEXECUTEINFO documentation for hProcess field you'll see that:
A handle to the newly started application. This member is set on return and is always NULL unless fMask is set to SEE_MASK_NOCLOSEPROCESS. Even if fMask is set to SEE_MASK_NOCLOSEPROCESS, hProcess will be NULL if no process was launched. For example, if a document to be launched is a URL and an instance of Internet Explorer is already running, it will display the document. No new process is launched, and hProcess will be NULL.
Note ShellExecuteEx does not always return an hProcess, even if a process is launched as the result of the call. For example, an hProcess does not return when you use SEE_MASK_INVOKEIDLIST to invoke IContextMenu.
Note if you're running a new process just to open an URL and get a server side generated file then you should follow Damien's suggestion and use a WebClient.DownloadFile().

Process.Start() can return a null reference:
Return Value
Type: System.Diagnostics.Process
A new Process component that is associated with the process resource, or null, if no process resource is started (for example, if an existing process is reused).
(Emphasis mine)
When that happens, you'll get a NullReferenceException when trying to call WaitForExit()

Related

Interrupt a running process with IPC

I have two processes in a Win Form application. In the first process I have a methode "checkIfTrue" which has a return value of boolean. The methode in the first process will get some information from the second process by IPC (I use WCF with named pipes) and will return, depand on the information from the second process true or false.
My problem how can I interrupt the first process? The method in the first process ask the second process for information, when the second process got the information and will send back the result to the first process. In the first process the result will not be process before the methode "checkIfTrue" are finished.
The second process will call a method "synchronizeResults" via IPC and transfer the results. The methode "synchronizeResults" store the result in a ConcurrentDictionary. My plan was to stop the methode "checkIfTrue" in first process until the Dictionary is filled. But the methode "synchronizeResults" is not calling by IPC until methode "checkIfTrue" is finished.
Normally i would fire a event when the result are send back from process 2, but in this case I need the result before the methode is finished.
The main reason while it doesnt work was my CallbackService-Class. I had forgot to mark the class with
[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Multiple)].
When a callback is made from the service to client, only one thread is spawned because by default the concurrency mode is set to “single”.
Here's [a link] (https://blogs.msdn.microsoft.com/dsnotes/2013/09/18/wcf-callback-operations-are-invoked-sequentially/)

Iterating over running processes works fine just once

I would like to retrieve information about all running processes that match a certain name pattern. I do that by using the following code I found online, which apparently is supposed to help with some privilige issues on Windows Vista and above. Sadly, that does not work for me. I am executing the following code as administrator.
The Natives.OpenProcess works fine the first time it is being called, but fails for every after call that by returning IntPtr.Zero and GetLastWin32Error() returns "Access Denied".
public static string GetExecutablePathAboveVista(int ProcessId)
{
var buffer = new StringBuilder(1024);
IntPtr hprocess = Natives.OpenProcess(ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, ProcessId);
if (hprocess != IntPtr.Zero)
{
try
{
int size = buffer.Capacity;
if (Natives.QueryFullProcessImageName(hprocess, 0, buffer, out size))
{
return buffer.ToString();
}
}
finally
{
Natives.CloseHandle(hprocess);
}
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, ..) give you ERROR_ACCESS_DENIED when and only when you have no SE_DEBUG_PRIVILEGE enabled. so can be only 2 case: or before first call GetExecutablePathAboveVista you have enabled SE_DEBUG_PRIVILEGE in thread (if it have token) or process token. and before second/next calls you direct or faster of all indirect disable this privilege or impersonate thread with another token. or possible you say confuse processes - first time you open one process (id) and second time you try open another process (id) - not clear from your code.
I am executing the following code as administrator.
this is not enough. this mean only that in your process token exist SE_DEBUG_PRIVILEGE. (with default windows settings, however this can be changed) but you need that this privilege will be enabled in token, not just exist.
also
that match a certain name pattern
if you need only process name without full path - you already have it when you enumerate all running processes.
also exist undocumented SystemProcessIdInformation information class for ZwQuerySystemInformation - with it you can got full path of process without open it and have any privileges.

Wait properties windows dialog before continue script

I had a piece of code to display the properties window of a file,
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = #"C:\Users\nyongrand\Desktop\Internet Download Manager.lnk";
psi.Verb = "properties";
Process process = Process.Start(psi);
process.WaitForExit(); //This give me exception, Object reference not set to an instance of an object.
what I want is to wait until the window properties is closed, because if my code closed the properties window will be closed as well, I need a solution between, my code is able to wait for the properties window closed, or my code can exit without closing the properties window.
The exception you're getting means that process is null at the time you try to call its WaitForExit member method. So the question you should be asking is why.
Start with the documentation for the overload of the Process.Start function that you're calling to see what it actually returns. Sure enough, it returns a Process object, but only under certain conditions:
Return Value
Type: System.Diagnostics.Process
A new Process component that is associated with the process resource, or null if no process resource is started (for example, if an existing process is reused).
And, from the "Remarks" section:
Note: If the address of the executable file to start is a URL, the process is not started and null is returned.
So, if an existing process is re-used, the Process.Start method will return null. And you cannot call methods on null.
Try replacing
Process process = Process.Start(psi);
with
Process process = new Process();
if(process.Start(psi))
{
process.WaitForExit();
}
else
{
//Do something here to handle your process failing to start
}
The problem you face with your code is that Process.Start() returns a Boolean. It's not a factory for Process objects.

What happens here: Process.GetCurrentProcess().MainModule.ModuleName;?

I seem to be a bit confused how the following call works:
string str = Process.GetCurrentProcess().MainModule.ModuleName;
I know it's the same as doing the following:
Process pvar = new Process();
ProcessModule pmvar = pvar.MainModule;
string str2 = pmvar.ModuleName;
But I need a detailed explanation how it's possible to ex. call the MainModule non-static property in the class ProcessModule since I haven't created an instanse of the Process class explicitly!
Does the GetCurrentProcess() method automatically create an instanse to work on, since it's not required to do so?
You haven't created an instance of Process, but this returns one for you:
Process process = Process.GetCurrentProcess();
That's very different from the new Process() call you've got in the second snippet. So your first statement is actually equivalent to:
Process process = Process.GetCurrentProcess();
ProcessModule module = process.MainModule;
string moduleName = module.ModuleName;
GetCurrentProcess() returns a reference to a Process object representing the currently executing process.
The call to GetCurrentProcess() return a Process instance - your second codesnippet is not what really happens...
GetCurrentProcess returns a reference to an instance. It could be a newly created instance, or a reference to an existing instance from some kind of cache. Anyways it is an instance, which can be used to call the MainModule getter.
According to the MSDN documentation, this is the behavior of GetCurrentProcess:
Use this method to create a new Process instance and associate it with the process resource on the local computer.

Process.HasExited returns true even though process is running?

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");
}
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.
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.
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.
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.)
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).
There's two possibilities, the process object continues to hold a reference to the process, so it has exited, but it hasn't yet been deleted. Or you have a second instance of the process running. You should also compare the process Id to make sure. Try this.
....
// Start the program
process.Start();
while (!process.HasExited)
Thread.Sleep( 500 );
Process[] p = Process.GetProcessesByName( "testprogram" );
if ( p.Length != 0 && p[0].Id == process.id && ! p[0].HasExited)
throw new Exception("Oh oh");
For a start, is there an issue with using Process.WaitForExit rather than polling it?
Anyway, it is technically possible for the process to exit from a usable point of view but the process still be around briefly while it does stuff like flush disk cache. Is the log file especially large (or any operation it is performing heavy on disk writes)?
As per MSDN documentation for HasExited.
If a handle is open to the process,
the operating system releases the
process memory when the process has
exited, but retains administrative
information about the process, such as
the handle, exit code, and exit time.
Probably not related, but it's worth noting.
If it's only a problem 1/10 of the time, and the process disappears after a second anyway, depending on your usage of HasExited, try just adding another delay after the HasExited check works, like
while (!process.HasExited)
DoStuff();
Thread.Sleep(500);
Cleanup();
and see if the problem persists.
Personally, I've always just used the Exited event handler instead of any kind of polling, and a simplistic custom wrapper around System.Diagnostics.Process to handle things like thread safety, wrapping a call to CloseMainWindow() followed by WaitForExit(timeout) and finally Kill(), logging, et cetera, and never encountered a problem.
Maybe the problem is in the testprogram? Does this code nicely flush/close etc.? It seems to me if testprogram writes a file to disk, the file should at least be available (empty or not)
If you have web application, and your external program/process is generating files (write to disk) check if your IIS have rights to write to that folder if not on properties security add permission for your IIS user, that was the reason in my case, i was receiving process.HasExited =true, but produced files from the process was not completed, after struggling for a while i add full permissions to the folder where process was writhing and process.Refresh() as Zarathos described from above and everything was working as expected.
Use process_name.Refresh() before checking whether process has exited or not. Refresh() will clear all the cached information related to the process.

Categories