美文网首页
C# Process 进程类操作进程

C# Process 进程类操作进程

作者: wwmin_ | 来源:发表于2021-01-22 15:21 被阅读0次

Process 简介

Process 类主要提供对本地和远程进程的访问,并提供对本地进程的启动、停止等操作。

进程:

进程是操作系统级别的一个基本概念,操作系统就将某个程序加载到内存中时,既包含该程序所需要的资源,同时还对这些资源进行基本的内存边界管理。

Process类:

负责启动和停止本机进程,获取或设置进程优先级,确定进程是否响应,是否已经退出,以及获取系统正在运行的所有进行列表和各进程资源占用情况。也可以查询远城计算机上进程相关信息,包括进程内的线程集合、加载模块(.dll文件和.exe文件)和性能信息(如当前进程使用的内存量)

Process类

Process 类的常用属性和方法如下表所示。

属性或方法 说明
MachineName 属性,获取关联进程正在其上运行的计算机的名称
Id 属性,获取关联进程的唯一标识符
ExitTime 属性,获取关联进程退出的时间
ProcessName 属性,获取该进程的名称
StartTime 属性,获取关联进程启动的时间
Threads 属性,获取在关联进程中运行的一组线程
TotalProcessorTime 属性,获取此进程的总的处理器时间
UserProcessorTime 属性,获取此进程的用户处理器时间
Close() 方法,释放与此组件关联的所有资源
CloseMainWindow() 方法,通过向进程的主窗口发送关闭消息来关闭拥有用户界面的进程
Dispose() 方法,释放由 Component 使用的所有资源
GetCurrentProcess() 方法,获取新的 Process 组件,并将其与当前活动的进程关联
GetProcesses() 方法,为本地计算机上的每个进程资源创建一个新的 Process 组件
GetProcesses(String) 方法,为指定计算机上的每个进程资源创建一个新的 Process 组件
GetProcessesByName(String) 方法,创建新的 Process 组件的数组,并将它们与本地计算机上共享指定的进程名称的所有进程资源关联
Kill() 方法,立即停止关联的进程
Start() 方法,启动(或重用)此 Process 组件的 Startinfo 属性指定的进程资源, 并将其与该组件关联
Start(String) 方法,通过指定文档或应用程序文件的名称来启动进程资源,并将资源与新的 Process 组件关联
 using (Process proc = new Process())
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ":" + file);
    proc.StartInfo.WorkingDirectory = file;
    proc.StartInfo.FileName = file + "command.bat";
    //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示,经实践可行
    //proc.StartInfo.CreateNoWindow = true;//不显示程序窗口

    proc.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
    proc.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
    proc.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
    proc.StartInfo.RedirectStandardError = true;//重定向标准错误输出
    proc.Start();//启动程序
                 //proc.StandardInput.WriteLine("exit");//向cmd窗口写入命令
    proc.StandardInput.AutoFlush = true;
    proc.WaitForExit();
    stopwatch.Stop();
    Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ":" + file + ",共耗时:" + stopwatch.ElapsedMilliseconds / 1000d + "s");
    var msg = proc.StandardOutput.ReadToEnd();
    FileStream newFs = new FileStream(file + "Output/output.txt", FileMode.Append);
    StreamWriter sw = new StreamWriter(newFs, Encoding.ASCII);
    sw.Write(DateTime.Now);
    sw.Write(msg);
    sw.Flush();
    sw.Close();
    newFs.Close();
    proc.Close();
};

相关示例:

using System.Diagnostics;

//获取所有进程
void GetAllProcesses()
{
    //获取该系统下所有进程
    Process[] processes = Process.GetProcesses();
    //    foreach (var process in processes)
    //    {
    //        process.ProcessName.Dump();
    //    }
    string.Join<String>(",", processes.Select(p => p.ProcessName)).Dump();
}
//GetAllProcesses();

//打开特定进程
void StartNewProcess(string processName)
{
    Process p = new Process();//创建Process 类的对象
    p.StartInfo.FileName = processName;
    p.Start();//启动进程
}
//StartNewProcess("notepad");//此名称即可打开notepad进程,即打开记事本程序

Thread.Sleep(100);
//停止特定进程
bool StopProcess(string processName)
{
    Process[] processes = Process.GetProcessesByName(processName);
    if (processes.Length == 0) return false;
    try
    {
        foreach (var p in processes)
        {
            //判断是否处于运行状态
            if (!p.HasExited)
            {
                //关闭进程
                p.Kill();
                p.Close();
                p.Dispose();
            }
        }
        return true;
    }
    catch (Exception)
    {

        throw;
    }
}
//StopProcess("notepad").Dump("关闭特定进程");//所有记事本进程都会被关闭

//打开另一个cmd进程,然后控制其运行,并获取该控制台的输出内容
void StartOtherCmdWindowAndReadInfo(string file)
{
    using (Process proc = new Process())
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ":" + file);
        proc.StartInfo.WorkingDirectory = file;
        proc.StartInfo.FileName = file + "command.bat";
        //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示,经实践可行
        //proc.StartInfo.CreateNoWindow = true;//不显示程序窗口

        proc.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
        proc.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
        proc.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
        proc.StartInfo.RedirectStandardError = true;//重定向标准错误输出
        proc.Start();//启动程序
                     //proc.StandardInput.WriteLine("exit");//向cmd窗口写入命令
        proc.StandardInput.AutoFlush = true;
        proc.WaitForExit();
        stopwatch.Stop();
        Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ":" + file + ",共耗时:" + stopwatch.ElapsedMilliseconds / 1000d + "s");
        var msg = proc.StandardOutput.ReadToEnd();
        FileStream newFs = new FileStream(file + "Output/output.txt", FileMode.Append);
        StreamWriter sw = new StreamWriter(newFs, Encoding.ASCII);
        sw.Write(DateTime.Now);
        sw.Write(msg);
        sw.Flush();
        sw.Close();
        newFs.Close();
        proc.Close();
    };
}

//调用ping.exe服务
public static class PingServicecs
{
    private const int TIME_OUT = 100;
    private const int PACKET_SIZE = 512;
    private const int TRY_TIMES = 2;
    //检查时间的正则
    private static Regex _reg = new Regex(@"时间=(.*?)ms", RegexOptions.Multiline | RegexOptions.IgnoreCase);
    /// <summary>
    /// 结果集
    /// </summary>
    /// <param name="stringcommandLine">字符命令行</param>
    /// <param name="packagesize">丢包大小</param>
    /// <returns></returns>
    public static string LauchPing(string stringcommandLine, int packagesize)
    {
        Process process = new Process();
        process.StartInfo.Arguments = stringcommandLine;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.FileName = "ping.exe";
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.StandardOutputEncoding = Encoding.UTF8;//将编码设置成utf-8,保证中文不会乱码。
        process.Start();
        return process.StandardOutput.ReadToEnd();//返回结果

    }
    /// <summary>
    /// 转换字节
    /// </summary>
    /// <param name="strBuffer">缓冲字符</param>
    /// <param name="packetSize">丢包大小</param>
    /// <returns></returns>
    private static float ParseResult(string strBuffer, int packetSize)
    {
        if (strBuffer.Length < 1)
            return 0.0F;
        MatchCollection mc = _reg.Matches(strBuffer);
        if (mc == null || mc.Count < 1 || mc[0].Groups == null)
            return 0.0F;
        if (!int.TryParse(mc[0].Groups[1].Value, out int avg))
            return 0.0F;
        if (avg <= 0)
            return 1024.0F;
        return (float)packetSize / avg * 1000 / 1024;
    }
    /// <summary>
    /// 通过Ip或网址检测调用Ping 返回 速度
    /// </summary>,
    /// <param name="strHost"></param>
    /// <returns></returns>
    public static string Test(string strHost, int trytimes, int PacketSize, int TimeOut)
    {
        return LauchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, trytimes, PacketSize, TimeOut), PacketSize);
    }
    /// <summary>
    /// 地址
    /// </summary>
    /// <param name="strHost"></param>
    /// <returns></returns>
    public static string Test(string strHost)
    {
        return LauchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, TRY_TIMES, PACKET_SIZE, TIME_OUT), PACKET_SIZE);
    }
}

PingServicecs.Test("192.168.9.161").Dump();//打印ping的输出信息

另外:
windows系统下 cmd 命令默认输出cp936编码,即gb2312.
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;将编码设置成utf-8,保证中文不会乱码。

本文作者:wwmin
微信公众号: DotNet技术说
本文链接:https://www.jianshu.com/p/01d60c48dc30
关于博主:评论和私信会在第一时间回复。或者[直接私信]我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,关注点赞, 您的鼓励是博主的最大动力!

相关文章

  • C# Process 进程类操作进程

    Process 简介 Process 类主要提供对本地和远程进程的访问,并提供对本地进程的启动、停止等操作。 进程...

  • 浏览器的进程

    进程 (process) 和线程 (thread) 进程(process)和线程(thread)是操作系统的基本概...

  • python的进程

    1.进程Process multiprocessing模块提供了一个Process类来创建一个进程对象 创建子进程...

  • C# Process进程管理类

    首先必须添加引用 using System.Diagnostics; (1)启动进程 Process p = ne...

  • 多进程

    创建进程 方式一:直接继承Process类 daemon 表示守护进程,当为子进程上设置为True时,主进程结束(...

  • Process网络编辑

    1. Process 创建进程的类:Process([group [, target [, name [, arg...

  • Nginx系列-初始化

    Nginx 进程分为主进程(master process)和若干工作进程(work process),其中工作进程...

  • 43.进程和线程和事件循环

    操作系统-进程-线程 线程和进程是操作系统中的两个概念: 进程(process):计算机已经运行的程序,是操作系统...

  • 第三周周末自习 (2018-10-27)

    一、多进程 python中,windows可以用multiprocessing模块引入多进程,使用Process类...

  • Day11进程和线程

    多进程 multiprocessing multiprocessing模块提供了一个Process类来代表一个进程...

网友评论

      本文标题:C# Process 进程类操作进程

      本文链接:https://www.haomeiwen.com/subject/ogyrzktx.html