Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

c# - How to determine Windows.Diagnostics.Process from ServiceController

This is my first post, so let me start by saying HELLO!

I am writing a windows service to monitor the running state of a number of other windows services on the same server. I'd like to extend the application to also print some of the memory statistics of the services, but I'm having trouble working out how to map from a particular ServiceController object to its associated Diagnostics.Process object, which I think I need to determine the memory state.

I found out how to map from a ServiceController to the original image name, but a number of the services I am monitoring are started from the same image, so this won't be enough to determine the Process.

Does anyone know how to get a Process object from a given ServiceController? Perhaps by determining the PID of a service? Or else does anyone have another workaround for this problem?

Many thanks, Alex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

System.Management should work for you in this case. Here's a sample to get you started:

using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Management;
class Program
{
    static void Main(string[] args)
    {
        foreach (ServiceController scTemp in ServiceController.GetServices())
        {
            if (scTemp.Status == ServiceControllerStatus.Stopped)
                continue;    // stopped, so no process ID!

            ManagementObject service = new ManagementObject(@"Win32_service.Name='" + scTemp.ServiceName + "'");
            object o = service.GetPropertyValue("ProcessId");
            int processId = (int) ((UInt32) o);
            Process process = Process.GetProcessById(processId);
            Console.WriteLine("Service: {0}, Process ID: {1}", scTemp.ServiceName, processId);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...