C#中进程的挂起与恢复

时间:2022-01-14 23:42:09

1. 源起:

仍然是模块化编程所引发的需求。产品经理难伺候,女产品经理更甚之~:p

纯属戏谑,技术方案与产品经理无关,芋头莫怪!

vcu10项目重构,要求各功能模块以独立进程方式实现,比如:音视频转换模块,若以独立进程方式实现,如何控制其暂停、继续等功能呢?

线程可以suspend、resume,c#内置的process没有此类方法,咋整?

山穷水尽疑无路,柳暗花明又一村。情到浓时清转薄,此情可待成追忆!

前篇描述了进程间数据传递方法,此篇亦以示例演示其间控制与数据交互方法。

 2、未公开的api函数:ntsuspendprocess、ntresumeprocess

此类函数在msdn中找不到。

思其原因,概因它们介于windows api和 内核api之间,威力不容小觑。怕二八耙子程序员滥用而引发事端,因此密藏。

其实还有个ntterminateprocess,因process有kill方法,因此可不用。

但再隐秘的东西,只要有价值,都会被人给翻出来,好酒不怕巷子深么!

好,基于其,设计一个进程管理类,实现模块化编程之进程间控制这个需求。

3、processmgr

直上代码吧,封装一个进程管理单元:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
public static class processmgr
 {
  /// <summary>
  /// the process-specific access rights.
  /// </summary>
  [flags]
  public enum processaccess : uint
  {
   /// <summary>
   /// required to terminate a process using terminateprocess.
   /// </summary>
   terminate = 0x1,
   /// <summary>
   /// required to create a thread.
   /// </summary>
   createthread = 0x2,
   /// <summary>
   /// undocumented.
   /// </summary>
   setsessionid = 0x4,
   /// <summary>
   /// required to perform an operation on the address space of a process (see virtualprotectex and writeprocessmemory).
   /// </summary>
   vmoperation = 0x8,
   /// <summary>
   /// required to read memory in a process using readprocessmemory.
   /// </summary>
   vmread = 0x10,
   /// <summary>
   /// required to write to memory in a process using writeprocessmemory.
   /// </summary>
   vmwrite = 0x20,
   /// <summary>
   /// required to duplicate a handle using duplicatehandle.
   /// </summary>
   duphandle = 0x40,
   /// <summary>
   /// required to create a process.
   /// </summary>
   createprocess = 0x80,
   /// <summary>
   /// required to set memory limits using setprocessworkingsetsize.
   /// </summary>
   setquota = 0x100,
   /// <summary>
   /// required to set certain information about a process, such as its priority class (see setpriorityclass).
   /// </summary>
   setinformation = 0x200,
   /// <summary>
   /// required to retrieve certain information about a process, such as its token, exit code, and priority class (see openprocesstoken, getexitcodeprocess, getpriorityclass, and isprocessinjob).
   /// </summary>
   queryinformation = 0x400,
   /// <summary>
   /// undocumented.
   /// </summary>
   setport = 0x800,
   /// <summary>
   /// required to suspend or resume a process.
   /// </summary>
   suspendresume = 0x800,
   /// <summary>
   /// required to retrieve certain information about a process (see queryfullprocessimagename). a handle that has the process_query_information access right is automatically granted process_query_limited_information.
   /// </summary>
   querylimitedinformation = 0x1000,
   /// <summary>
   /// required to wait for the process to terminate using the wait functions.
   /// </summary>
   synchronize = 0x100000
  }
  [dllimport("ntdll.dll")]
  private static extern uint ntresumeprocess([in] intptr processhandle);
  [dllimport("ntdll.dll")]
  private static extern uint ntsuspendprocess([in] intptr processhandle);
  [dllimport("kernel32.dll", setlasterror = true)]
  private static extern intptr openprocess(
   processaccess desiredaccess,
   bool inherithandle,
   int processid);
  [dllimport("kernel32.dll", setlasterror = true)]
  [return: marshalas(unmanagedtype.bool)]
  private static extern bool closehandle([in] intptr handle);
  public static void suspendprocess(int processid)
  {
   intptr hproc = intptr.zero;
   try
   {
    // gets the handle to the process
    hproc = openprocess(processaccess.suspendresume, false, processid);
    if (hproc != intptr.zero)
     ntsuspendprocess(hproc);
   }
   finally
   {
    // don't forget to close handle you created.
    if (hproc != intptr.zero)
     closehandle(hproc);
   }
  }
  public static void resumeprocess(int processid)
  {
   intptr hproc = intptr.zero;
   try
   {
    // gets the handle to the process
    hproc = openprocess(processaccess.suspendresume, false, processid);
    if (hproc != intptr.zero)
     ntresumeprocess(hproc);
   }
   finally
   {
    // don't forget to close handle you created.
    if (hproc != intptr.zero)
     closehandle(hproc);
   }
  }
 }

4、进程控制

我权且主进程为宿主,它通过process类调用子进程,得其id,以此为用。其调用代码为:

?
1
2
3
4
5
6
7
8
9
10
11
12
private void runtestprocess(bool hidden = false)
 {
  string apppath = path.getdirectoryname(application.executablepath);
  string testapppath = path.combine(apppath, "testapp.exe");
  var pi = new processstartinfo();
  pi.filename = testapppath;
  pi.arguments = this.handle.tostring();
  pi.windowstyle = hidden ? processwindowstyle.hidden : processwindowstyle.normal;
  this.childprocess = process.start(pi);
  txtinfo.text = string.format("子进程id:{0}\r\n子进程名:{1}", childprocess.id, childprocess.processname);
  ...
 }

控制代码为:    

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void btnwork_click(object sender, eventargs e)
  {
   if (this.childprocess == null || this.childprocess.hasexited)
    return;
   if ((int)btnwork.tag == 0)
   {
    btnwork.tag = 1;
    btnwork.text = "恢复";
    processmgr.suspendprocess(this.childprocess.id);
   }
   else
   {
    btnwork.tag = 0;
    btnwork.text = "挂起";
    processmgr.resumeprocess(this.childprocess.id);
   }
  }

子进程以一定时器模拟其工作,向主进程抛进度消息:

?
1
2
3
4
5
6
7
8
9
private void timer_tick(object sender, eventargs e)
 {
  if (progressbar.value < progressbar.maximum)
   progressbar.value += 1;
  else
   progressbar.value = 0;
  if (this.hosthandle != intptr.zero)
   sendmessage(this.hosthandle, wm_progress, 0, progressbar.value);
 }

代码量就这么的少,简单吧……

5、效果图:

为示例,做了两个图,其一为显示子进程,其二为隐藏子进程。

C#中进程的挂起与恢复

实际项目调用独立进程模块,是以隐藏方式调用的,以宿主展示其处理进度,如此图:

C#中进程的挂起与恢复

后记:

扩展思路,一些优秀的开源工具,如youtube_dl、ffmpeg等,都以独立进程方式存在,且可通过cmd管理通信。

以此进程控制原理,可以基于这些开源工具,做出相当不错的gui工具出来。毕竟相对于强大的命令行,人们还是以简单操作为方便。

原文链接:http://www.cnblogs.com/crwy/p/6622319.html