Skip to content

Commit 8597794

Browse files
committed
Работа с процессами ОС #108
1 parent daf990d commit 8597794

File tree

6 files changed

+176
-12
lines changed

6 files changed

+176
-12
lines changed

src/ScriptEngine.HostedScript/Library/ProcessContext.cs

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,14 @@ namespace ScriptEngine.HostedScript.Library
1515
[ContextClass("Процесс", "Process")]
1616
public class ProcessContext : AutoContext<ProcessContext>, IDisposable
1717
{
18-
private System.Diagnostics.Process p;
18+
private System.Diagnostics.Process _p;
1919
private StdTextReadStream _stdOutContext;
2020
private StdTextReadStream _stdErrContext;
21+
private StdTextWriteStream _stdInContext;
2122

2223
public ProcessContext(System.Diagnostics.Process p)
2324
{
24-
this.p = p;
25+
this._p = p;
2526
}
2627

2728
[ContextProperty("ПотокВывода", "StdOut")]
@@ -30,7 +31,7 @@ public StdTextReadStream StdOut
3031
get
3132
{
3233
if(_stdOutContext == null)
33-
_stdOutContext = new StdTextReadStream(p.StandardOutput);
34+
_stdOutContext = new StdTextReadStream(_p.StandardOutput);
3435
return _stdOutContext;
3536
}
3637
}
@@ -41,23 +42,34 @@ public StdTextReadStream StdErr
4142
get
4243
{
4344
if (_stdErrContext == null)
44-
_stdErrContext = new StdTextReadStream(p.StandardError);
45+
_stdErrContext = new StdTextReadStream(_p.StandardError);
4546
return _stdErrContext;
4647
}
4748
}
4849

50+
[ContextProperty("ПотокВвода", "StdIn")]
51+
public StdTextWriteStream StdIn
52+
{
53+
get
54+
{
55+
if (_stdInContext == null)
56+
_stdInContext = new StdTextWriteStream(_p.StandardInput);
57+
return _stdInContext;
58+
}
59+
}
60+
4961
[ContextMethod("Запустить", "Start")]
5062
public void Start()
5163
{
52-
p.Start();
64+
_p.Start();
5365
}
5466

5567
[ContextProperty("Завершен","HasExited")]
5668
public bool HasExited
5769
{
5870
get
5971
{
60-
return p.HasExited;
72+
return _p.HasExited;
6173
}
6274
}
6375

@@ -66,14 +78,29 @@ public int ExitCode
6678
{
6779
get
6880
{
69-
return p.ExitCode;
81+
return _p.ExitCode;
7082
}
7183
}
7284

7385
[ContextMethod("ОжидатьЗавершения", "WaitForExit")]
7486
public void WaitForExit()
7587
{
76-
p.WaitForExit();
88+
_p.WaitForExit();
89+
}
90+
91+
[ContextProperty("Идентификатор", "ProcessId")]
92+
public int ProcessId
93+
{
94+
get
95+
{
96+
return _p.Id;
97+
}
98+
}
99+
100+
[ContextMethod("Завершить","Stop")]
101+
public void Stop()
102+
{
103+
_p.Kill();
77104
}
78105

79106
public void Dispose()
@@ -90,7 +117,13 @@ public void Dispose()
90117
_stdErrContext = null;
91118
}
92119

93-
p.Dispose();
120+
if(_stdInContext != null)
121+
{
122+
_stdInContext.Dispose();
123+
_stdInContext = null;
124+
}
125+
126+
_p.Dispose();
94127
}
95128
}
96129
}

src/ScriptEngine.HostedScript/Library/StdTextReadStream.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ public string ReadLine()
3939
return _reader.ReadLine();
4040
}
4141

42+
[ContextMethod("Закрыть", "Close")]
43+
public void Close()
44+
{
45+
_reader.Close();
46+
}
47+
4248
public void Dispose()
4349
{
4450
_reader.Dispose();
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using ScriptEngine.Machine;
2+
using ScriptEngine.Machine.Contexts;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.IO;
6+
using System.Linq;
7+
using System.Text;
8+
9+
namespace ScriptEngine.HostedScript.Library
10+
{
11+
[ContextClass("ПотокВводаТекста", "TextInputStream")]
12+
public class StdTextWriteStream : AutoContext<StdTextWriteStream>, IDisposable
13+
{
14+
private StreamWriter _writer;
15+
16+
public StdTextWriteStream(StreamWriter writer)
17+
{
18+
_writer = writer;
19+
}
20+
21+
[ContextMethod("Записать","Write")]
22+
public void Write(string data)
23+
{
24+
_writer.Write(data);
25+
}
26+
27+
[ContextMethod("ЗаписатьСтроку", "WriteLine")]
28+
public void WriteLine(string data)
29+
{
30+
_writer.WriteLine(data);
31+
}
32+
33+
[ContextMethod("Закрыть", "Close")]
34+
public void Close()
35+
{
36+
_writer.Close();
37+
}
38+
39+
public void Dispose()
40+
{
41+
_writer.Dispose();
42+
}
43+
}
44+
}

src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,43 @@ public ProcessContext CreateProcess(string cmdLine, string currentDir = null, bo
237237

238238
}
239239

240+
/// <summary>
241+
/// Выполняет поиск процесса по PID среди запущенных в операционной системе
242+
/// </summary>
243+
/// <param name="PID">Идентификатор процесса</param>
244+
/// <returns>Процесс. Если не найден - Неопределено</returns>
245+
[ContextMethod("НайтиПроцессПоИдентификатору", "FindProcessById")]
246+
public IValue FindProcessById(int PID)
247+
{
248+
System.Diagnostics.Process process;
249+
try
250+
{
251+
process = System.Diagnostics.Process.GetProcessById(PID);
252+
}
253+
catch (ArgumentException)
254+
{
255+
return ValueFactory.Create();
256+
}
257+
258+
return ValueFactory.Create(new ProcessContext(process));
259+
260+
}
261+
262+
/// <summary>
263+
/// Выполняет поиск процессов с определенным именем
264+
/// </summary>
265+
/// <param name="name">Имя процесса</param>
266+
/// <returns>Массив объектов Процесс.</returns>
267+
[ContextMethod("НайтиПроцессыПоИмени", "FindProcessesByName")]
268+
public IValue FindProcessesByName(string name)
269+
{
270+
var processes = System.Diagnostics.Process.GetProcessesByName(name);
271+
var contextWrappers = processes.Select(x => new ProcessContext(x));
272+
273+
return new ArrayImpl(contextWrappers);
274+
275+
}
276+
240277
[ContextMethod("КаталогПрограммы","ProgramDirectory")]
241278
public string ProgramDirectory()
242279
{

src/ScriptEngine.HostedScript/ScriptEngine.HostedScript.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
<Compile Include="Library\Net\TCPServer.cs" />
7777
<Compile Include="Library\ProcessContext.cs" />
7878
<Compile Include="Library\StdTextReadStream.cs" />
79+
<Compile Include="Library\StdTextWriteStream.cs" />
7980
<Compile Include="Library\SystemGlobalContext.cs" />
8081
<Compile Include="Library\GuidWrapper.cs" />
8182
<Compile Include="Library\KeyAndValueImpl.cs" />

tests/process.os

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
ВсеТесты.Добавить("ТестДолжен_ПолучитьПутьКOscript");
1010
ВсеТесты.Добавить("ТестДолжен_ПрочитатьВыводOscriptСразу");
1111
ВсеТесты.Добавить("ТестДолжен_ПрочитатьВыводOscriptПострочно");
12+
ВсеТесты.Добавить("ТестДолжен_ЗаписатьВоВходнойПотокПроцесса");
13+
ВсеТесты.Добавить("ТестДолжен_НайтиПроцессПоИмени");
14+
ВсеТесты.Добавить("ТестДолжен_НайтиПроцессПоPID");
1215

1316
Возврат ВсеТесты;
1417

@@ -32,7 +35,7 @@
3235

3336
Стр = НормализоватьПереводыСтрок(Поток.Прочитать());
3437

35-
юТест.ПроверитьРавенство(ШтатыйВыводOscript(), Стр);
38+
юТест.ПроверитьРавенство(ШтатныйВыводOscript(), Стр);
3639

3740
КонецПроцедуры
3841

@@ -52,11 +55,51 @@
5255
КонецЦикла;
5356
КонецЦикла;
5457

55-
юТест.ПроверитьРавенство(ШтатыйВыводOscript(), НормализоватьПереводыСтрок(Стр));
58+
юТест.ПроверитьРавенство(ШтатныйВыводOscript(), НормализоватьПереводыСтрок(Стр));
5659

5760
КонецПроцедуры
5861

59-
Функция ШтатыйВыводOscript()
62+
Процедура ТестДолжен_ЗаписатьВоВходнойПотокПроцесса() Экспорт
63+
64+
Процесс = СоздатьПроцесс("sort",,Истина, Истина);
65+
Процесс.Запустить();
66+
67+
Процесс.ПотокВвода.ЗаписатьСтроку("2");
68+
Процесс.ПотокВвода.ЗаписатьСтроку("1");
69+
Процесс.ПотокВвода.ЗаписатьСтроку("3");
70+
Процесс.ПотокВвода.Закрыть();
71+
72+
Вывод = Процесс.ПотокВывода.Прочитать();
73+
74+
Эталон = НормализоватьПереводыСтрок("1
75+
|2
76+
|3
77+
|");
78+
79+
юТест.ПроверитьРавенство(Эталон, НормализоватьПереводыСтрок(Вывод));
80+
81+
КонецПроцедуры
82+
83+
Процедура ТестДолжен_НайтиПроцессПоИмени() Экспорт
84+
85+
МассивПроцессов = НайтиПроцессыПоИмени("oscript");
86+
юТест.ПроверитьБольшеИлиРавно(МассивПроцессов.Количество(), 1);
87+
88+
КонецПроцедуры
89+
90+
Процедура ТестДолжен_НайтиПроцессПоPID() Экспорт
91+
92+
МассивПроцессов = НайтиПроцессыПоИмени("oscript");
93+
94+
ИД = МассивПроцессов[0].Идентификатор;
95+
96+
Процесс = НайтиПроцессПоИдентификатору(ИД);
97+
98+
юТест.ПроверитьРавенство(Процесс.Идентификатор, ИД);
99+
100+
КонецПроцедуры
101+
102+
Функция ШтатныйВыводOscript()
60103

61104
Текст =
62105
"1Script Execution Engine. Version 1.0.9.0

0 commit comments

Comments
 (0)