简体   繁体   English

检查是否有从Windows Service运行的进程

[英]Check if there's a process running from Windows Service

Currently, I am using: 目前,我正在使用:

private bool IsProcessRunning(string ProcessName)
{
    foreach(Process clsProcess in Process.GetProcesses())
    {
        if(clsProcess.ProcessName.Contains(ProcessName))
        {
            return true;
        }
    }
    return false;
}

This bool returns true if process is running. 如果进程正在运行,则此布尔值将返回true This works fine in Console/WinForms application, but it's not working when I am trying to check if a process is running from a Windows Service. 这在Console / WinForms应用程序中工作正常,但是当我尝试检查某个进程是否从Windows Service运行时却无法正常工作。 As we all know, Windows Services are running on different SID than other applications. 众所周知,Windows服务与其他应用程序在不同的SID上运行。 So, does anyone know how can I check if an application is running on a different Session? 因此,有人知道如何检查应用程序是否在其他会话上运行吗?

You might want to look into the ServiceController. 您可能需要研究ServiceController。 I do not know if this might assist you somewhat? 我不知道这是否会对您有所帮助?

Below is an example on how to use it 以下是有关如何使用它的示例

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
  case ServiceControllerStatus.Running:
    return "Running";
  case ServiceControllerStatus.Stopped:
    return "Stopped";
  case ServiceControllerStatus.Paused:
    return "Paused";
  case ServiceControllerStatus.StopPending:
    return "Stopping";
  case ServiceControllerStatus.StartPending:
    return "Starting";
  default:
    return "Status Changing";
}

If you have to retrieve the status again, you will have to refresh the status before checking again 如果必须再次获取状态,则必须刷新状态然后再检查

sc.Refresh()

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

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