Stopping current application and running update application - delphi

I am trying to write my own update source code to update my application from the web
basically I use two INI files. One on the web and one on the client side. The client side holds the current version number and the url to the server side ini. The server side ini holds the newest version and the url to the new download.
Anyways, all seems to work great. The file downloads great, but I would like to know the how one goes about closing the current application to run the new downloaded file (installer)

Why not simply run the updater and the immediately close the current application?
ShellExecute(nil, nil, PathToUpdater, nil, nil, SW_SHOWNORMAL);
Application.Terminate; // Or some other way
Surely the updater doesn't mind that the original process lives a few milliseconds into its lifetime?

The normal procedure is like this:
The main program detects that an update is ready.
The main program silently downloads the update to a temporary location. The download is performed in a background thread.
When the download is complete and verified, the main program restarts.
Whenever the program starts and notices that there is a new update waiting to be installed it terminates and runs a separate executable that performs the update.
When the update is complete, the program is restarted again.
The main benefit of this is that the user is not compelled to wait for the download to occur. A process which may take time and may fail. Thus giving the user as little downtime as possible.
There is a tricky scenario to handle. That's when the program starts the updater and then shuts itself down. If the main process doesn't close before the update opens the executable, then the updater can fail. The most elegant way to handle this is for the main program to pass its PID to the updater. The updater can then open a handle to that process and wait until it is signaled.
An alternative approach, quite similar, goes like this:
The main program detects that an update is ready and fires off a separate executable to perform the update. Or, the main program periodically fires off the updater to check whether or not there is an update available.
The update process silently downloads the update to a temporary location.
When the download is complete and verified, the updater signals the main process to terminate.
Once the main process has terminated (the updater waits for it to do so), the updater performs the update.
When the update is complete, the main program is restarted.
To be honest, the second approach seems more attractive to me. It has a much better separation of concerns. The main program is concerned with its business. The updater is concerned with its job. Obviously there has to be interaction and cooperation between them, but this is kept to a bare minimum.

Related

Why does OpenProcess() return a non 0 value when the process ID is no longer running

I'm starting a new instance of another application using CreateProcess from Example and I end up saving the PID so that I can later check if that process is still running.
I'm using to following method to check if it's running or not:
procedure TfrmRSM.Button1Click(Sender: TObject);
begin
var
ahandle := OpenProcess(PROCESS_ALL_ACCESS, true, aPID);
if ahandle = 0 then
ShowMessage('is not running')
else
ShowMessage('is running');
CloseHandle(ahandle);
end;
The code above should return 0 when the process is no longer running but it still returns a number greater than 0
I am closing the handle after using CreateProcess
Whats to propper way to check if a PID is running if the method I'm using is incorrect? I'm only able to find methods that use the application name.
I'm starting a new instance of another application using CreateProcess from Example and I end up saving the PID so that I can later check if that process is still running.
The correct way to handle this is to keep open the HANDLE that CreateProcess() gives you, and then you can query it via WaitForSingleObject() or GetExitCodeProcess() to see if the process has terminated or not, and then close the HANDLE when you no longer need it.
In comments, you mention that your launching app may terminate and be restarted separate from the target process. In that case, you could close the HANDLE if you still have it open, saving its PID and creation date/time somewhere you can get it back from, and then when your app restarts it can enumerate running processes (alternatively) to see if the target EXE is still running and has a matching PID and date/time, and if so then open a new HANDLE to that PID. Just be careful, because this does introduce a small race condition where the target process might terminate after you detect its presence and its PID could get recycled before you have a chance to open it. So you might need to re-validate the HANDLE's info again after opening it.
Otherwise, during your app's shutdown (or even before), you can off-load the open HANDLE from CreateProcess() to a separate helper process that stays running in the background monitoring the HANDLE, and then your main app can get the HANDLE back from that helper after restarting. Or, perform the actual CreateProcess() call in the helper to begin with, so the HANDLE monitoring stays within a single process at all times, and let your main app query the helper for status when needed.
I'm using to following method to check if it's running or not:
That will not work, as you don't know whether the PID is still valid, or even still refers to the same process you are interested in. Once that process has terminated, its PID can be recycled at any time for use with a new process.
The code above should return 0 when the process is no longer running but it still returns a number greater than 0
The only way OpenProcess() can return non-zero is if the specified PID is actually running. But that does not guarantee it is the same process you are interested in. At the very least, after OpenProcess() returns a non-zero HANDLE, you can query that HANDLE for its info (EXE file path, creation date/time, etc) to see if it is the same process you are expecting. If the info does not match, the PID was recycled.
Why does OpenProcess() return a non 0 value when the process ID is no
longer running?
This is probably an undefined behavior or the PID has been recycled by Windows.
I want to check if a process I created is still running later even
after I quit my application and opened it again.
You said you cannot change the process. One work around is to use an intermediate and very simple process to launch the target process. The intermediate process can use any IPC (for example shared memory of shared file) to talk to the main process to inform it about running target process. This intermediate process will run the target process and update a flag that the main process can query (In my example in shared memory).
The intermediate process can also simply keep a file open for exclusive access while the target process is running. The main process can try to open the file and if it succeed, then the target process is done (Intermediate process use WaitForSingleObjector WaitForMultipleObject to wait for target process termination).
To wait for a process to end, simply use WaitForSingleObject() on the process handle: when the process ends, the handle is signaled and the function returns WAIT_OBJECT_0. This ensures that you "look" at the handle the whole time it lives, instead of only inspecting it from time to time and otherwise leave it unattended.
Most likely you put this into a separate thread, and upon its ending you have your event to react to when the watched process ended. If you have multiple handles to look for, use WaitForMultipleObjects() - be aware that it can't handle more than 64 (MAXIMUM_WAIT_OBJECTS) handles at once.
Edit: when not being able to track a process handle entirely you can at least use GetProcessTimes() to check if the process you're looking at still started at the same time you looked at it last time - that should make it pretty distinctive: when the process handle is recycled by a new process then at least its starting time should differ.

How to wait for termination of itself

my currently running application (A1) needs to be terminated but as well as run some other application (A2). But I need to run application A2 after fully terminated of A1. Now I have something like this:
begin
Application.Terminate;
wait(2000); <<<<<<<
ShellExecute(A2)...
end;
To be more exact - I need to call installation (A2) and want to be sure A1 is not running, because A2 is installation of A1. Please imagine that termination could last more time or it shows some modal dialog...
Is there any easy way how to do it (wait for it)? Of course without communication with or changing of A2! A2 could be anything else in the future.
VladimĂ­r
I need to call installation (A2) and want to be sure A1 is not running.
This is impossible. You cannot execute code in a process that has terminated. Once the process has terminated there is nothing that can execute code.
You'll need a new process. Start the new process with the sole task of waiting on its parent to terminate, and then do whatever is needed once the parent has terminated.
If want to make a proper installer/updater program don't worry about when and how do you execute it but instead how it will detect if your application is running or not.
Now if your main application already has a mechanizm to prevent starting of multiple instances of your application you already have half the work done. How?
Such mechanizms publish the information about an instance of your application already running to be available by other programs.
Most common appraoch to do so is by registering a named Mutex. So when second instance of your application starts it finds out that it can't create a new Mutex with the same name becouse one already exists. So now in most cases second instance of your application sends a custom message to the first instance to bring that instance to the front (restore application) and then closes itself.
If you want to read more about different mechanizms to controling how many instances of your application can be running at the same time I suggest you check the next article:
http://delphi.about.com/od/windowsshellapi/l/aa100703a.htm
So how do you use such mechanizm for your installer/updater?
Just as you would check in second instance of your application to see if another instance is already running you check this in your installer/updater instead. You don't even need to do this schecking at the start of installer/updater. You can do it even later (downloading the update files first).
If there is an instance of your application running you broadcast a custom message. But this message is different from the one that one instance would send to another.
This will now tell your application that it is about to be updated so it should begin the closing procedure.
If you form this custom message in such a way that it also contains information about your installer/updater application.handle you give yourself the ability for your main application to send a return response in which it notifies the installer/updater in which state it is. For instnace:
asClosing (main application is just about to close)
asWaitinUserInput (main application is waiting for user to confirm save for instance)
asProcessing (main application is doing some lengthy processing so it can't shut down at this time)
And if there is no response in certain amount of time your installer could asume that your main application might be hung so it notifies the user that automatic closure of main application has failed and so that the user should close it manually and then retry the updating process.
Using such approach would allow you to start your installer/updater at any time during execution of your main application.
And not only that. You can start your installer/updater by double clicking its executable, by a shourtcut, by some other application or even by a windows task system.

Waiting for applications to finish loading [duplicate]

I have an application which needs to run several other applications in chain. I am running them via ShellExecuteEx. The order of running each of the apps is very important cause they are dependant on each other. For example:
Start(App1);
If App1.IsRunning then
Start(App2);
If App2.IsRunning then
Start(App3);
.........................
If App(N-1).IsRunning then
Start(App(N));
Everything works fine but there is a one possible problem:
ShellExecuteEx starts the application, and return almost immediately. The problem might arise when for example App1 has started properly but has not finished some internal tasks, it is not yet ready to use. But ShellExecuteEx is already starting App2 which depends on the App1, and App2 won't start properly because it needs fully initialized App1.
Please note, that I don't want to wait for App(N-1) to finish and then start AppN.
I don't know if this is possible to solve with ShellExecuteEx, I've tried to use
SEInfo.fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_NOASYNC;
but without any effect.
After starting the AppN application I have a handle to the process. If I assume that the application is initialized after its main window is created (all of Apps have a window), can I somehow put a hook on its message queue and wait until WM_CREATE appears or maybe WM_ACTIVATE? In pressence of such message my Application would know that it can move on.
It's just an idea. However, I don't know how to put such hook. So if you could help me in this or you have a better idea that would be great:)
Also, the solution must work on Windows XP and above.
Thanks for your time.
Edited
#Cosmic Prund: I don't understand why did you delete your answer? I might try your idea...
You can probably achieve what you need by calling WaitForInputIdle() on each process handle returned by ShellExecute().
Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.
If your application has some custom initialization logic that doesn't run in UI thread then WaitForInputIdle might not help. In that case you need a mechanism to signal the previous app that you're done initializing.
For signaling you can use named pipes, sockets, some RPC mechanism or a simple file based lock.
You can always use IPC and Interpocess Synchronization to make your application communicate with (and wait for, if needed) each other, as long as you code both applications.

Multithreaded (TThread) Delphi application will not terminate

I have written an application (using Delphi 2009) that allows a user to select a series of queries which can be run across a number of different systems. In order to allow queries to be run concurrently, each query is run in its own thread, using a TADOQuery object. This all works fine.
The problem that I have is when I try to close the application when a query is still running (and therefore a separate thread is active). When I create each thread, I record the thread's THandle in an array. When I try to close the application, if any threads are still running, I retrieve the thread's handle and pass it to TerminateThread, which should theoretically terminate the thread and allow the application to close. However, this doesn't happen. The main form's onClose event is triggered and it looks like the application is closing, but the process remains active and my Delphi interface appears as though the application is still running (i.e. "Run" button greyed out, debug view active etc.). I don't get control back to Delphi until I manually end the process (either Ctrl-F2 in Delphi or via Task Manager).
I am using TerminateThread because the query can take a long time to run (a few minutes in cases where we're dealing with a million or so records, which in the end user environment is perfectly possible) and while it is running, unless I'm mistaken, the thread won't be able to check the Terminated property and therefore won't be able to end itself if this were set to True until the query had returned, so I can't terminate the thread in the usual way (i.e. by checking the Terminated property). It may be the case that the user wants to exit the application while a large query is running, and in that case, I need the application to immediately end (i.e. all running threads immediately terminate) rather than forcing them to wait until all queries have finished running, so TerminateThread would be ideal but it isn't actually terminating the thread!
Can anyone help out here? Does anyone know why TerminateThread doesn't work properly? Can anyone suggest anything to get the threads running large ADO queries to immediately terminate?
You should be able to cancel an ADO Query by hooking the OnFetchProgress event, and setting the Eventstatus variable to esCancel. This should cause your query to terminate and allow the thread to close gracefully without having to resort to using TerminateThread.
Instead of using threads with TADOQuery, maybe you should consider using the async options of ADO.
ADOQuery1.ExecuteOptions := [eoAsyncExecute, eoAsyncFetch, eoAsyncFetch];
Then when your application close, you can call :
ADOQuery1.cancel;
As you can read in the msdn using TerminateThread is dangerous.
TerminateThread is a dangerous
function that should only be used in
the most extreme cases. You should
call TerminateThread only if you know
exactly what the target thread is
doing, and you control all of the code
that the target thread could possibly
be running at the time of the
termination.
But it also is very effective in killing threads. Are you sure you are right in your conclusions? Maybe the thread is killed, but another thread is still running? Maybe your handles are not thread handles? Could you show us some code? Or even better: A small working example we could try for ourselves?

Self Updating

What's the best way to terminate a program and then run additional code from the program that's being terminated? For example, what would be the best way for a program to self update itself?
You have a couple options:
You could use another application .exe to do the auto update. This is probably the best method.
You can also rename a program's exe while it is running. Hence allowing you to get the file from some update server and replace it. On the program's next startup it will be using the new .exe. You can then delete the renamed file on startup.
It'd be really helpful to know what language we're talking about here. I'm sure I could give you some really great tips for doing this in PowerBuilder or Cobol, but that might not really be what you're after! If you're talking Java however, then you could use a shut down hook - works great for me.
Another thing to consider is that most of the "major" apps I've been using (FileZilla, Paint.NET, etc.), are having the updaters uninstall the previous version of the app and then doing a fresh install of the new version of the application.
I understand this won't work for really large applications, but this does seem to be a "preferred" process for the small to medium size applications.
I don't know of a way to do it without a second program that the primary program launches prior to shutting down. Program 2 downloads and installs the changes and then relaunches the primary program.
We did something like this in our previous app. We captured the termination of the program (in .NET 2.0) from either the X or the close button, and then kicked off a background update process that the user didn't see. It would check the server (client-server app) for an update, and if there was one available, it would download in the background using BITS. Then the next time the application opened, it would realize that there was a new version (we set a flag) and popped up a message alerting the user to the new version, and a button to click if they wanted to view the new features added to this version.
It makes it easier if you have a secondary app that runs to do the updates. You would execute the "updater" app, and then inside of it wait for the other process to exit. If you need access to the regular apps DLLs and such but they also need updating, you can run the updater from a secondary location with already updated DLLs so that they are not in use in the original location.
If you're using writing a .NET application, you might consider using ClickOnce. If you need quite a bit of customization, you might look elsewhere.
We have an external process that performs updating for us. When it finds an update, it downloads it to a secondary folder and then waits for the main application to exit. On exit, it replaces all of the current files. The primary process just kicks the update process off every 4 hours. Because the update process will wait for the exit of the primary app, the primary app doesn't have to do any special processing other than start the update application.
This is a side issue, but if you're considering writing your own update process, I would encourage you to look into using compression of some sort to (1) save on download and (2) provide one file to pull from an update server.
Hope that makes sense!

Resources