繁体   English   中英

在父退出后保持子进程处于活动状态

[英]Keep child process alive after parent exits

我正在为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#中启动一个不是孩子的新流程,它本身就存在?

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

例如:

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

您可以使用调度程序服务。 虽然其他人建议这可以直接完成。

  1. 确保“计划”服务(也称为“任务计划程序”)正在运行。
  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,我强烈建议您阅读本文,了解如何正确使用如何使用System.Diagnostics.Process 另外,我建议在Process.Start周围使用一个好的包装器API,就像我自己的ProcessRunner类一样,这样你就不会遇到死锁,等待进程退出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM