2011-08-04 49 views
4

我正在为Windows服务写一个autoupdater。这是我想要的工作(请让我知道如果有一个更好的解决方案)父进程退出后保持子进程生效

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 child starts the parent service. 

我卡在#2,因为当我停止父服务的子进程被终止。我如何在C#中启动一个不是子进程的新进程,它本身就是存在的?

回答

7

您可以使用Process.Start将启动一个单独的独立过程:

例如为:

System.Diagnostics.Process.Start(@"C:\windows\system32\notepad.exe"); 
+0

是从运行不同:方法P =新工艺(); p.start(); ??我的理解是这种方式创建了一个子进程。 – Matthew

+0

我不确定这将在随后被停止的服务中起作用。 –

+0

是的,他们是不同的。以这种方式启动类似于从“运行”对话框启动某些内容。它没有与其父母关联。如果你转向MSDN,他们会详细解释过载之间的区别。 – Mrchief

0

你可以使用调度程序服务。虽然其他人认为这可以直接完成。

  1. 确保“Schedule”服务(又名“Task Scheduler”)正在运行。
  2. 运行AT.EXESCHTASKS.EXE命令行实用工具来安排子进程的执行。
  3. 等待停止事件到达服务,如果您没有在超时期限内收到它,则说明您有问题;)根据计划的方式,您可以尝试再次运行它。

我宁愿schtasks的命令,类似以下内容:

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"

这将产生以下输出:

WARNING: Task may not run because /ST is earlier than current time.
SUCCESS: The scheduled task "My Updater" has successfully been created.

要小心,如果该名称的任务已经存在,将会产生覆盖提示。创建任务后,你可以在任何时候运行:

C:\> schtasks.exe /run /tn "My Updater"
SUCCESS: Attempted to run the scheduled task "My Updater".

最后,你可以删除任务,但需要确认:

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.

所以要使用这些命令,您只需生成您选择的调度程序。当然这也可以通过编程来完成;然而,我从来没有想出如何;)

由于使用std :: out/err和std :: in,我强烈推荐阅读这篇文章如何使用How to use System.Diagnostics.Process correctly。另外,我会建议使用一个好的wrapper API around Process.Start, like my own ProcessRunner class,这样你就不会陷入僵局,等待进程退出。

+0

感谢您的帮助。我不喜欢这个想法,一个简单的事实是,通过使用任务计划程序,我可以在处理重要事情的时候终止服务。 – Matthew