【发布时间】:2011-06-10 19:39:55
【问题描述】:
我有一个 C# 窗口服务,它运行一个批处理文件 (.bat),而该文件又执行一个 java 应用程序。该服务运行 .bat 文件 (cmd.exe) 没有问题。但是,当我尝试停止窗口服务时,cmd.exe 进程并没有死。如果我再次启动服务,则会堆叠一个新的 cmd 进程。
如何杀死正在运行的 cmd.exe 进程?
代码:
private const string BATCH_FILE_PATH_APPKEY = "Service_Batch_File_Path";
private const string BATCH_FILE_DEFAULT = "Service.bat";
private static Process _proc;
private static bool _hasStarted = false;
public AService()
{
InitializeComponent();
_proc = new Process();
}
protected override void OnStart(string[] args)
{
try
{
string appDirectory = System.Windows.Forms.Application.ExecutablePath;
appDirectory = appDirectory.Substring(0, appDirectory.LastIndexOf("\\"));
string workingDirectory = appDirectory;
string batchFilePath = string.Empty;
batchFilePath = workingDirectory + "Service.bat";
// Make sure it exists
_proc.StartInfo = new ProcessStartInfo(batchFilePath);
_proc.StartInfo.CreateNoWindow = true;
_proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_proc.Start();
_hasStarted = true;
}
catch (System.Exception ex)
{
eventLog1.WriteEntry(ex.ToString() + "\n\nStack Trace:\n" + ex.StackTrace);
OnStop();
}
}
protected override void OnStop()
{
if (_hasStarted)
_proc.CloseMainWindow();
//_proc.Close();
}
TIA, 亚历克斯。
【问题讨论】:
-
应该把 _proc.Close() 注释掉吗?
-
理想情况下,您可以告诉您的 java 应用程序优雅地终止。它自己关闭,它运行的 cmd.exe 关闭,每个人都很高兴。
标签: c# multithreading command-line windows-services