Keep child process alive after parent exits
I'm writing an autoupdater for a windows service. This is how I want it to work (please let me know if there is a better solution)
1) The service launches a child Process (the updater).
2) The child stops the parent service (I'm using sc.exe).
3) The child applies the updated .exe and .dll files for the parent.
4) The c开发者_如何学Gohild starts the parent service.
I'm stuck on #2 because a the child process is killed when I stop the parent service. How can I launch a new process in C# that is not a child, just exists by itself?
You can use Process.Start
which will start a separate independent process:
E.g.:
System.Diagnostics.Process.Start(@"C:\windows\system32\notepad.exe");
You could use the scheduler service. Although others are suggesting this can be done directly.
- Ensure the "Schedule" service (aka "Task Scheduler") is running.
- Run the
AT.EXE
, orSCHTASKS.EXE
command-line utility to schedule the execution of the child process. - Wait for the stop event to reach the service, if you don't recieve it within a timeout period, you have a problem ;) Depending on how it was scheduled, you can try to run it again.
I would prefer the schtasks command, similar to the following:
C:\> schtasks.exe /create /tn "My Updater" /sc once /ru System /sd 01/01/1999 /st 00:00 /tr "C:\Windows\System32\cmd.exe /c dir c: > c:\temp\ran.txt"
This should produce the following output:
WARNING: Task may not run because /ST is earlier than current time.
SUCCESS: The scheduled task "My Updater" has successfully been created.
Be careful, if the task by that name already exists a prompt to overwrite will be produced. After the task is created, you can run it at any time:
C:\> schtasks.exe /run /tn "My Updater"
SUCCESS: Attempted to run the scheduled task "My Updater".
Lastly, you can remove the task, but a confirmation is required:
C:\> schtasks.exe /delete /tn "My Updater"
WARNING: Are you sure you want to remove the task "My Updater" (Y/N)? y
SUCCESS: The scheduled task "My Updater" was successfully deleted.
So to use these commands, you only need to spawn the scheduler of your choice. Of course this can also be done programatically; however, I've never figured out how exactly ;)
Due to the use of both std::out/err and std::in, I highly recommend reading this article on how to use the How to use System.Diagnostics.Process correctly. Additionally, I would recommend using a good wrapper API around Process.Start, like my own ProcessRunner class so you don't wind up deadlocked waiting for the process to exit.
精彩评论