Somewhere in the application I create a instance of proc which is of Process type, something like this:
proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.FileName = Settings.Instance.OBSExeFile;
proc.Exited += (a, b) => doSomething();
proc.Start();
proc.WaitForInputIdle();
on Form.Closing Event, I want to close it, gently, if it's still open.
I find no other way to do this with native stuff within the .NET (neither Close() nor Kill() nor CloseMainWindow() seemed to fit my needs) so I eneded up doing sending WM_CLOSE to the application and calling Process.WaitForExit(), like this:
if (proc != null && !proc.HasExited) {
if(SendMessage(proc.MainWindowHandle, WM_CLOSE, 0, IntPtr.Zero) == 0)
proc.WaitForExit();
}
My question is: Am I missing something in the sense of mixing this being dangerous in any way? Can WaitForExit()hang for ever, for example?
Based on the information you provided I think good approach will be create a Windows service instead of .exe. Then you will have full control of process.
Inside windows service you can create a code which "gently" close current service when stop command will be send to it.
send a message to it, and have it close itself (in any way that you see fit). I have a set of programs that do this, I use a udp broadcast to 127.0.0.1 for this.
Related
I am making an application in which i want to execute some database queries just before system get shut down. I am using this code -
static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
e.Cancel = true;
MessageBox.Show("Shut down canceled");
}
I did execute this application and tried to shut down the system and this code captured the shut down event also but the problem is after showing message box it shows this screen also- [I can't post the image as i don't have 10 points.]
it shows the name of my application that stopped the system to get shut down and it also provide "Force Shut down button" , i dont want this screen to be displayed as user can forcefully shut down the system before completion of execution of my queries.
Need expert advices on this, thanks a lot in advance.
The Short Reliable Answer:
On any recent Windows version, you can try to cancel shutdown but Windows may decide to ignore you; this is sadly by design. If you absolutely have to finish operations before your process is terminated, the right place to do this is in the SessionEnded handler. If you have tasks that must complete before your process terminates, you must not return from your SessionEnded handler until all your work is done (so your queries, etc. have finished.)
So instead of (or as well as, if you prefer) handling SessionEnding, handle SessionEnded and do you work there:
static void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e)
{
WaitForQueriesToFinishOrSaveState(); // new code
}
How you implement that waiting will depend on your application; if you need to run queries afresh you may be able to do them therein, or you may need to Thread.Join() or otherwise wait for background tasks to complete; but it must be a blocking wait (so you need to not return from the function until you're done).
Since you can't absolutely stop shutdown, there's perhaps little point in attempting the cancellation in this case, so I'd recommend not setting e.Cancel in SessionEnding at all. On older Windows versions this was more meaningful, very much less so now unfortunately.
It's also recommended by the API docs not to do any significant work in SessionEnding (including message boxes), but to set any flags you need to return immediately and then do the work in SessionEnded. (Unproven aside: I'm suspicious that if you don't return quickly enough, this may hasten the appearance of the "programs are misbehaving, do you want to kill them" screen for the user, as Windows believes you're not playing nice any more.)
Behind the Scenes:
Setting e.Cancel indicates to Windows that you'd like the session not to end; but the user still gets a look in; and Windows may decide to ignore your request for any reason it feels pertinent. That's just the way the cookie crumbles. You may find hacks that work situationally, but there's no API or approach which is Microsoft-approved and therefore likely to work consistently now and in the future.
Under the covers, Windows is sending your process' windows a WM_QUERYENDSESSION message, which .NET receives for you and translates into the SessionEnding event) and will pass your cancellation (or lack of) back to Windows; returning TRUE if you don't cancel, FALSE if you do.
After this, Windows takes a look at all process' requests and depending on the cause of the shutdown and other factors may well still decide to go ahead despite such requests. It may also alert the user if processes are not cooperating and give them the option of killing the process.
Whether you handle WM_QUERYENDSESSION (SessionEnding) or not, you always get one last chance to clean up: you're sent a WM_ENDSESSION message (translated into SessionEnded). The tricky part is that you have to do all your vital tasks before all your SessionEnded handlers have returned!
Once Windows hears back from its WM_ENDSESSION (SessionEnded) call, all bets are off as far as your application's lifetime is concerned and Windows can terminate your process at any point.
Raymond Chen covered this quite expertly and quite recently.
http://blogs.msdn.com/b/oldnewthing/archive/2013/06/27/10429232.aspx
As a footnote, SystemEvents.SessionEnded is a convenience; if yo have a top level application window you can bypass it entirely and achieve the same via:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x16) // WM_ENDSESSION
{
WaitForQueriesToFinishOrSaveState();
m.Result = IntPtr.Zero;
return;
}
base.WndProc(ref m);
}
in shutdown command there's a switch for abort shutdown. you have to call this command by your c# code
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine(#"shutdown -a");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
I'm writing a small updater for my app.
My flow would be like this:
app.exe -> call process(updater.exe) -> app.close()
Then, updater check if app is closed, then overwrites app.exe and other satellite assemblies.
So I need to do something like this: launch my C# exe app, fire a process for updater.exe, then close app, but without closing child process.
There's a way to build this kind of fire-and-forget process in .NET?
Thank you,
Nando
Look at the Process object. You would just call Process.Start like so:
System.Diagnostics.Process.Start("updater.exe");
Yes, I'm doing so, but seems that Process don't start...
I made a small helper class, called Updater:
Updater.CheckUpdates()
--> starts a Process who call "updater.exe -check", and that works (when process finished, control return to my main app). I evaluate return code of process, and the I set Updater.UpdatesAvalilable bool flag, if necessary.
Updater.ApplyUpdates()
--> starts a Process who call "updater.exe -update", that do the update work.
So, my code is like this:
Updater.CheckUpdates();
if (Updater.UpdatesAvailable)
{
Updater.ApplyUpdates();
System.Environment.Exit(0);
}
Process in Updater.ApplyUpdates() never run.
I know, is not elegant code, but I don't know how to achieve my goal. :-)
Thank you!
Nando
Good morning guys.
I found a way to make it work, it seems.
In my helper class I wired events for getting stdIO and stdError, just to log something; removing those, I get my work done: process start and main exit! :-)
Just to make all know about it: my process declaration is now like this:
Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo = new ProcessStartInfo();
process.StartInfo.Arguments = "-update";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.FileName = "updater.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
process.Start();
Thank you all!
Nando
I am making a program for handheld PDAs using .net 2.0 compact framework and I have this one part which I'm not proud of and I was hoping for a more elegant solution.
Basically the problem is another process using my file in this case its Windows Media Player. I start the process by passing the file location to Process.Start but it seems the process returned is short lived and it is spawning another process? So I tried looking up how to get child process information but had some problems with that (i think no processes were being returned for some reason).
So i currently do this dodgy fix
string processName = item.Text;
Process proc = Process.Start(processName, null);
if (!proc.Start())
MessageBox.Show("Failed to start process", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
else
{
IntPtr newWindow = IntPtr.Zero;
TimeSpan limit = TimeSpan.FromSeconds(3);
DateTime start = DateTime.Now;
DateTime now = start;
// do while the following:
// window is not null
// window is not ourself
// under 3 seconds
do
{
newWindow = Win32.GetForegroundWindow();
now = DateTime.Now;
// taking too long
if (now - start > limit)
break;
}
while (newWindow == IntPtr.Zero || newWindow == this.Handle);
if (newWindow != IntPtr.Zero && newWindow != this.Handle)
{
uint processID = 0;
if (Win32.GetWindowThreadProcessId(newWindow, out processID) != 0)
{
//const int stringSize = 1024;
//StringBuilder sb = new StringBuilder(1024);
//Win32.GetWindowText(newWindow, sb, stringSize);
m_processes.Add(new ProcessIDWithName(processID, processName));
}
}
}
As you can see I don't like it and it's unreliable however it does work for now (i needed a solution whether it was bad or not).
Why do I need the process ID? Because windows media player is keeping the file open on me and I cannot move/delete the file and therefore I need to kill the process off before I do so. I could do a similar fix with FindWindow but I was thinking more generically as it might not be a media file opened in windows media player.
So basically I would like a better solution if possible!
Also if you wondering why I'm not using a Stopwatch its because it doesn't seem to exist in .net 2.0 cf, also I don't need accuracy to that extent.
There are loads of questions that pop up here.
Why aren't you executing media player itself instead of shellexecuting the name of the target file?
How do you know when the media is done playing in order to close the file?
Why not use the toolhelp APIs to simply enumerate processes instead of the wacky GetForegroundWindow/GetWindowsThreadProcessId shenanigans?
Why aren't you just using the Media Player ActiveX control instead of this kludge so you'd actually have control over things?
If you intend to make this generic for any file (i.e. not just media, but maybe something like the Word viewer, etc) then you're really out of luck and need to rethink whatever it is you're trying to do (you've not told us what you're trying to achieve, only how you['ve decided to implement it). Applications don't normally close in WinMo, they typically just lose focus of get minimized, so you don't really know when a user is "done" with the file.
The application associated with the file may already be running, so terminating it yourself is an unfriendly thing to do.
The target application really is not designed to give you a callback when it's done with any particular file.
I have no experience with PDA programming, bu you can try to use Job objects (see http://msdn.microsoft.com/en-us/library/ms684847.aspx#job_object_functions). With respect of CreateJobObject you can create a new job. Then you create a suspended process and use AssignProcessToJobObject to assign the new process to th job object. Then you can resume the process.
The advantage of job object is, that you can receive full control of all child processes of the job. You can use TerminateJobObject to terminate all processes. If you create creates an I/O completion port to wait for the end of the direct started process and all it's child processes or monitor of all child processes created and much more. If you need I could post some code examples of links to code examples.
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.
I'm currently writing myself a little C# back up program. I'm using a standard windows form for the interface, and am calling cmd.exe as a new process, and then using XCOPY from within this new process. Every thing's working great, except for this last feature I want to add in, which is the ability to break the operation.
From a native command prompt, I can do this cleanly with ctrl+c, but try as I might, I can't replicate this functionality using the winforms and process approach. I've tried redirecting the standardinput and using that to send consolespecialkeys.ControlC to the process, I've also tried sending 0x03 and "/x03", both of which I've read on other forum posts are hex code for ctrl+c. Nothing I'm sending is registered though, and exiting the process kills the user interface, but leaves the xcopy.exe working in the background. Killing xcopy.exe manually results in it leaving the file it was copying half copied and corrupted, not something that happens using the ctrl+c in a command prompt.
Am I missing something blindingly obvious? I'm new-ish to C#, so I'll hold my hands up and admit this is most likely me being slow, or misunderstanding how the process is working with cmd.exe. However, since processes support standard input redirection, it seems like something that should work... to me at least. I've put the basic outline of my code below, in case it helps identify where I'm messing up.
string XCopyArguments = "\"" + dir.FullName + "\" \"" + destination + "\" /D /S /I /E";
Process XCopyProcess = new Process();
ProcessStartInfo XCopyStartInfo = new ProcessStartInfo();
XCopyStartInfo.FileName = "CMD.exe ";
XCopyStartInfo.RedirectStandardError = true;
XCopyStartInfo.RedirectStandardOutput = true;
XCopyStartInfo.RedirectStandardInput = true;
XCopyStartInfo.UseShellExecute = false;
XCopyStartInfo.CreateNoWindow = true;
XCopyStartInfo.Arguments = " /D /c XCOPY " + XCopyArguments;
XCopyProcess.EnableRaisingEvents = true;
XCopyProcess.StartInfo = XCopyStartInfo;
XCopyProcess.Start();
XCopyProcess.WaitForExit(15000);
int ExitCode = XCopyProcess.ExitCode;
if (ExitCode > 0 & !XCopyProcess.HasExited)
{
XCopyProcess.Kill();
}
XCopyProcess.Dispose();
Many thanks in advance for any help anyone can offer.
I don't want to be a besserwisser, but I think you'd be much better off doing the copying inside your program. Using File, Directory and the other classes in the System.IO namespace, it's really simple, and leaves you in full control to report progress, cancel operations etc.
Yes, doing the operation in .NET would be easier. BUT, I need to send ctrl-c to a process also and I don't have that option.
So can we please get an answer to this question?
EDIT: Do I have to post a duplicate to get an answer? And no, #j0rd4n didn't answer the question.
Like the others said, there are better ways to accomplish that particular task. However, that doesn't answer your question. I use a similar technique to what you have shown here for automating various tasks and find it quite useful. Sometimes things go very badly though and you want the process to bail out before things get worse. ;p
Here is the problem with your example:
XCopyStartInfo.CreateNoWindow = true;
Set it to false and it will then process XCopyProcess.CloseMainWindow() and XCopyProcess.Close(). Much cleaner than using Kill().
It would require fewer code lines to just loop over the subdirectories and files and copy them one by one and then you wouldn't have to worry about controling another process...
Sorry it's in VB.NET.
Declare Function GenerateConsoleCtrlEvent Lib "kernel32" ( _
ByVal dwCtrlEvent As Integer, _
ByVal dwProcessGroupId As Integer _
) As Integer
Private Const CTRL_C_EVENT As Integer = 0
Private Sub SendCtrlC()
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
' send a Ctrl-C to this process
GenerateConsoleCtrlEvent(CTRL_C_EVENT, currentpid)
' send a Ctrl-C to the cmd process
GenerateConsoleCtrlEvent(CTRL_C_EVENT, cmdpid)
End Sub
I've successfully sent a CTRL-C combination to an cmd.exe process created with SW_HIDE--i.e, a hidden cmd.exe window.
The technique was to use EnumWindows to identify the process and get it's window handle (it still has a handle to process messages even if its not visible).
Next, I used PostMessage to post a ctrl-c combination to the process. This had the same effect as if a user had hit 'ctrl-c' while the window was active.
To do this from C#, you would want to probably visit http://pinvoke.net/ - a lifesaver when it comes to writing Win32 API function prototypes in C#.
You'll have to manually kill the process if you want to handle the copying this way. In your code above, you are calling XCopyProcess.WaitForExit(...). This is a blocking call so the parent C# process will halt at that point until the child process has finished or the time-interval has elapsed.
What you could do is instead of blocking, you can sleep in a loop routinely checking if the user has requested to kill the process via your C# UI. If you receive this event, you explicitly kill the process. Otherwise, you wait for another interval until the process is finished.
EDIT: I do agree with the other comments, though. Copy directly from the .NET framework instead of using xcopy.