Process.cs 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. //
  2. // System.Diagnostics.Process.cs
  3. //
  4. // Authors:
  5. // Dick Porter ([email protected])
  6. // Andreas Nahr ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. //
  9. // (C) 2002 Ximian, Inc.
  10. // (C) 2003 Andreas Nahr
  11. // (c) 2004 Novell, Inc. (http://www.novell.com)
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.IO;
  35. using System.ComponentModel;
  36. using System.ComponentModel.Design;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.InteropServices;
  39. using System.Collections;
  40. using System.Threading;
  41. namespace System.Diagnostics {
  42. [DefaultEvent ("Exited"), DefaultProperty ("StartInfo")]
  43. [Designer ("System.Diagnostics.Design.ProcessDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
  44. public class Process : Component
  45. {
  46. [StructLayout(LayoutKind.Sequential)]
  47. private struct ProcInfo
  48. {
  49. public IntPtr process_handle;
  50. /* If thread_handle is ever needed for
  51. * something, take out the CloseHandle() in
  52. * the Start_internal icall in
  53. * mono/metadata/process.c
  54. */
  55. public IntPtr thread_handle;
  56. public int pid; // Contains -GetLastError () on failure.
  57. public int tid;
  58. public string [] envKeys;
  59. public string [] envValues;
  60. public bool useShellExecute;
  61. };
  62. IntPtr process_handle;
  63. int pid;
  64. bool enableRaisingEvents;
  65. ISynchronizeInvoke synchronizingObject;
  66. /* Private constructor called from other methods */
  67. private Process(IntPtr handle, int id) {
  68. process_handle=handle;
  69. pid=id;
  70. }
  71. [MonoTODO]
  72. public Process() {
  73. }
  74. [MonoTODO]
  75. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  76. [MonitoringDescription ("Base process priority.")]
  77. public int BasePriority {
  78. get {
  79. return(0);
  80. }
  81. }
  82. [DefaultValue (false), Browsable (false)]
  83. [MonitoringDescription ("Check for exiting of the process to raise the apropriate event.")]
  84. public bool EnableRaisingEvents {
  85. get {
  86. return enableRaisingEvents;
  87. }
  88. set {
  89. if (process_handle != IntPtr.Zero)
  90. throw new InvalidOperationException ("The process is already started.");
  91. enableRaisingEvents = value;
  92. }
  93. }
  94. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  95. private extern static int ExitCode_internal(IntPtr handle);
  96. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  97. [MonitoringDescription ("The exit code of the process.")]
  98. public int ExitCode {
  99. get {
  100. if (process_handle == IntPtr.Zero)
  101. throw new InvalidOperationException ("Process has not been started.");
  102. int code = ExitCode_internal (process_handle);
  103. if (code == 259)
  104. throw new InvalidOperationException ("The process must exit before " +
  105. "getting the requested information.");
  106. return code;
  107. }
  108. }
  109. /* Returns the process start time in Windows file
  110. * times (ticks from DateTime(1/1/1601 00:00 GMT))
  111. */
  112. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  113. private extern static long ExitTime_internal(IntPtr handle);
  114. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  115. [MonitoringDescription ("The exit time of the process.")]
  116. public DateTime ExitTime {
  117. get {
  118. if (process_handle == IntPtr.Zero)
  119. throw new InvalidOperationException ("Process has not been started.");
  120. if (!HasExited)
  121. throw new InvalidOperationException ("The process must exit before " +
  122. "getting the requested information.");
  123. return(DateTime.FromFileTime(ExitTime_internal(process_handle)));
  124. }
  125. }
  126. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  127. [MonitoringDescription ("Handle for this process.")]
  128. public IntPtr Handle {
  129. get {
  130. return(process_handle);
  131. }
  132. }
  133. [MonoTODO]
  134. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  135. [MonitoringDescription ("Handles for this process.")]
  136. public int HandleCount {
  137. get {
  138. return(0);
  139. }
  140. }
  141. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  142. [MonitoringDescription ("Determines if the process is still running.")]
  143. public bool HasExited {
  144. get {
  145. if (process_handle == IntPtr.Zero)
  146. throw new InvalidOperationException ("Process has not been started.");
  147. int exitcode = ExitCode_internal (process_handle);
  148. if(exitcode==259) {
  149. /* STILL_ACTIVE */
  150. return(false);
  151. } else {
  152. return(true);
  153. }
  154. }
  155. }
  156. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  157. [MonitoringDescription ("Process identifier.")]
  158. public int Id {
  159. get {
  160. return(pid);
  161. }
  162. }
  163. [MonoTODO]
  164. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  165. [MonitoringDescription ("The name of the computer running the process.")]
  166. public string MachineName {
  167. get {
  168. return("localhost");
  169. }
  170. }
  171. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  172. [MonitoringDescription ("The main module of the process.")]
  173. public ProcessModule MainModule {
  174. get {
  175. return(this.Modules[0]);
  176. }
  177. }
  178. [MonoTODO]
  179. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  180. [MonitoringDescription ("The handle of the main window of the process.")]
  181. public IntPtr MainWindowHandle {
  182. get {
  183. return((IntPtr)0);
  184. }
  185. }
  186. [MonoTODO]
  187. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  188. [MonitoringDescription ("The title of the main window of the process.")]
  189. public string MainWindowTitle {
  190. get {
  191. return("null");
  192. }
  193. }
  194. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  195. private extern static bool GetWorkingSet_internal(IntPtr handle, out int min, out int max);
  196. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  197. private extern static bool SetWorkingSet_internal(IntPtr handle, int min, int max, bool use_min);
  198. /* LAMESPEC: why is this an IntPtr not a plain int? */
  199. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  200. [MonitoringDescription ("The maximum working set for this process.")]
  201. public IntPtr MaxWorkingSet {
  202. get {
  203. if(HasExited) {
  204. throw new InvalidOperationException("The process " + ProcessName + " (ID " + Id + ") has exited");
  205. }
  206. int min;
  207. int max;
  208. bool ok=GetWorkingSet_internal(process_handle, out min, out max);
  209. if(ok==false) {
  210. throw new Win32Exception();
  211. }
  212. return((IntPtr)max);
  213. }
  214. set {
  215. if(HasExited) {
  216. throw new InvalidOperationException("The process " + ProcessName + " (ID " + Id + ") has exited");
  217. }
  218. bool ok=SetWorkingSet_internal(process_handle, 0, value.ToInt32(), false);
  219. if(ok==false) {
  220. throw new Win32Exception();
  221. }
  222. }
  223. }
  224. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  225. [MonitoringDescription ("The minimum working set for this process.")]
  226. public IntPtr MinWorkingSet {
  227. get {
  228. if(HasExited) {
  229. throw new InvalidOperationException("The process " + ProcessName + " (ID " + Id + ") has exited");
  230. }
  231. int min;
  232. int max;
  233. bool ok=GetWorkingSet_internal(process_handle, out min, out max);
  234. if(ok==false) {
  235. throw new Win32Exception();
  236. }
  237. return((IntPtr)min);
  238. }
  239. set {
  240. if(HasExited) {
  241. throw new InvalidOperationException("The process " + ProcessName + " (ID " + Id + ") has exited");
  242. }
  243. bool ok=SetWorkingSet_internal(process_handle, value.ToInt32(), 0, true);
  244. if(ok==false) {
  245. throw new Win32Exception();
  246. }
  247. }
  248. }
  249. /* Returns the list of process modules. The main module is
  250. * element 0.
  251. */
  252. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  253. private extern ProcessModule[] GetModules_internal();
  254. private ProcessModuleCollection module_collection;
  255. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  256. [MonitoringDescription ("The modules that are loaded as part of this process.")]
  257. public ProcessModuleCollection Modules {
  258. get {
  259. if(module_collection==null) {
  260. module_collection=new ProcessModuleCollection(GetModules_internal());
  261. }
  262. return(module_collection);
  263. }
  264. }
  265. [MonoTODO]
  266. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  267. [MonitoringDescription ("The number of bytes that are not pageable.")]
  268. public int NonpagedSystemMemorySize {
  269. get {
  270. return(0);
  271. }
  272. }
  273. [MonoTODO]
  274. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  275. [MonitoringDescription ("The number of bytes that are paged.")]
  276. public int PagedMemorySize {
  277. get {
  278. return(0);
  279. }
  280. }
  281. [MonoTODO]
  282. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  283. [MonitoringDescription ("The amount of paged system memory in bytes.")]
  284. public int PagedSystemMemorySize {
  285. get {
  286. return(0);
  287. }
  288. }
  289. [MonoTODO]
  290. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  291. [MonitoringDescription ("The maximum amount of paged memory used by this process.")]
  292. public int PeakPagedMemorySize {
  293. get {
  294. return(0);
  295. }
  296. }
  297. [MonoTODO]
  298. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  299. [MonitoringDescription ("The maximum amount of virtual memory used by this process.")]
  300. public int PeakVirtualMemorySize {
  301. get {
  302. return(0);
  303. }
  304. }
  305. [MonoTODO]
  306. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  307. [MonitoringDescription ("The maximum amount of system memory used by this process.")]
  308. public int PeakWorkingSet {
  309. get {
  310. return(0);
  311. }
  312. }
  313. [MonoTODO]
  314. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  315. [MonitoringDescription ("Process will be of higher priority while it is actively used.")]
  316. public bool PriorityBoostEnabled {
  317. get {
  318. return(false);
  319. }
  320. set {
  321. }
  322. }
  323. [MonoTODO]
  324. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  325. [MonitoringDescription ("The relative process priority.")]
  326. public ProcessPriorityClass PriorityClass {
  327. get {
  328. return(ProcessPriorityClass.Normal);
  329. }
  330. set {
  331. }
  332. }
  333. [MonoTODO]
  334. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  335. [MonitoringDescription ("The amount of memory exclusively used by this process.")]
  336. public int PrivateMemorySize {
  337. get {
  338. return(0);
  339. }
  340. }
  341. [MonoTODO]
  342. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  343. [MonitoringDescription ("The amount of processing time spent in the OS core for this process.")]
  344. public TimeSpan PrivilegedProcessorTime {
  345. get {
  346. return(new TimeSpan(0));
  347. }
  348. }
  349. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  350. private extern static string ProcessName_internal(IntPtr handle);
  351. private string process_name=null;
  352. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  353. [MonitoringDescription ("The name of this process.")]
  354. public string ProcessName {
  355. get {
  356. if(process_name==null) {
  357. process_name=ProcessName_internal(process_handle);
  358. /* If process_name is _still_
  359. * null, assume the process
  360. * has exited
  361. */
  362. if(process_name==null) {
  363. throw new SystemException("The process has exited");
  364. }
  365. /* Strip the suffix (if it
  366. * exists) simplistically
  367. * instead of removing any
  368. * trailing \.???, so we dont
  369. * get stupid results on sane
  370. * systems
  371. */
  372. if(process_name.EndsWith(".exe") ||
  373. process_name.EndsWith(".bat") ||
  374. process_name.EndsWith(".com")) {
  375. process_name=process_name.Substring(0, process_name.Length-4);
  376. }
  377. }
  378. return(process_name);
  379. }
  380. }
  381. [MonoTODO]
  382. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  383. [MonitoringDescription ("Allowed processor that can be used by this process.")]
  384. public IntPtr ProcessorAffinity {
  385. get {
  386. return((IntPtr)0);
  387. }
  388. set {
  389. }
  390. }
  391. [MonoTODO]
  392. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  393. [MonitoringDescription ("Is this process responsive.")]
  394. public bool Responding {
  395. get {
  396. return(false);
  397. }
  398. }
  399. private StreamReader error_stream=null;
  400. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  401. [MonitoringDescription ("The standard error stream of this process.")]
  402. public StreamReader StandardError {
  403. get {
  404. if (error_stream == null) {
  405. throw new InvalidOperationException("Standard error has not been redirected");
  406. }
  407. return(error_stream);
  408. }
  409. }
  410. private StreamWriter input_stream=null;
  411. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  412. [MonitoringDescription ("The standard input stream of this process.")]
  413. public StreamWriter StandardInput {
  414. get {
  415. if (input_stream == null) {
  416. throw new InvalidOperationException("Standard input has not been redirected");
  417. }
  418. return(input_stream);
  419. }
  420. }
  421. private StreamReader output_stream=null;
  422. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  423. [MonitoringDescription ("The standard output stream of this process.")]
  424. public StreamReader StandardOutput {
  425. get {
  426. if (output_stream == null) {
  427. throw new InvalidOperationException("Standard output has not been redirected");
  428. }
  429. return(output_stream);
  430. }
  431. }
  432. private ProcessStartInfo start_info=null;
  433. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  434. [MonitoringDescription ("Information for the start of this process.")]
  435. public ProcessStartInfo StartInfo {
  436. get {
  437. if(start_info==null) {
  438. start_info=new ProcessStartInfo();
  439. }
  440. return(start_info);
  441. }
  442. set {
  443. if(value==null) {
  444. throw new ArgumentException("value is null");
  445. }
  446. start_info=value;
  447. }
  448. }
  449. /* Returns the process start time in Windows file
  450. * times (ticks from DateTime(1/1/1601 00:00 GMT))
  451. */
  452. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  453. private extern static long StartTime_internal(IntPtr handle);
  454. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  455. [MonitoringDescription ("The time this process started.")]
  456. public DateTime StartTime {
  457. get {
  458. return(DateTime.FromFileTime(StartTime_internal(process_handle)));
  459. }
  460. }
  461. [DefaultValue (null), Browsable (false)]
  462. [MonitoringDescription ("The object that is used to synchronize event handler calls for this process.")]
  463. public ISynchronizeInvoke SynchronizingObject {
  464. get { return synchronizingObject; }
  465. set { synchronizingObject = value; }
  466. }
  467. [MonoTODO]
  468. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden), Browsable (false)]
  469. [MonitoringDescription ("The number of threads of this process.")]
  470. public ProcessThreadCollection Threads {
  471. get {
  472. return(null);
  473. }
  474. }
  475. [MonoTODO]
  476. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  477. [MonitoringDescription ("The total CPU time spent for this process.")]
  478. public TimeSpan TotalProcessorTime {
  479. get {
  480. return(new TimeSpan(0));
  481. }
  482. }
  483. [MonoTODO]
  484. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  485. [MonitoringDescription ("The CPU time spent for this process in user mode.")]
  486. public TimeSpan UserProcessorTime {
  487. get {
  488. return(new TimeSpan(0));
  489. }
  490. }
  491. [MonoTODO]
  492. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  493. [MonitoringDescription ("The amount of virtual memory currently used for this process.")]
  494. public int VirtualMemorySize {
  495. get {
  496. return(0);
  497. }
  498. }
  499. [MonoTODO]
  500. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  501. [MonitoringDescription ("The amount of physical memory currently used for this process.")]
  502. public int WorkingSet {
  503. get {
  504. return(0);
  505. }
  506. }
  507. public void Close()
  508. {
  509. Dispose (true);
  510. }
  511. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  512. extern static bool Kill_internal (IntPtr handle, int signo);
  513. /* int kill -> 1 KILL, 2 CloseMainWindow */
  514. bool Close (int signo)
  515. {
  516. if (process_handle == IntPtr.Zero)
  517. throw new SystemException ("No process to kill.");
  518. int exitcode = ExitCode_internal (process_handle);
  519. if (exitcode != 259)
  520. throw new InvalidOperationException ("The process already finished.");
  521. return Kill_internal (process_handle, signo);
  522. }
  523. public bool CloseMainWindow ()
  524. {
  525. return Close (2);
  526. }
  527. [MonoTODO]
  528. public static void EnterDebugMode() {
  529. }
  530. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  531. private extern static IntPtr GetProcess_internal(int pid);
  532. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  533. private extern static int GetPid_internal();
  534. public static Process GetCurrentProcess() {
  535. int pid=GetPid_internal();
  536. IntPtr proc=GetProcess_internal(pid);
  537. if(proc==IntPtr.Zero) {
  538. throw new SystemException("Can't find current process");
  539. }
  540. return(new Process(proc, pid));
  541. }
  542. public static Process GetProcessById(int processId) {
  543. IntPtr proc=GetProcess_internal(processId);
  544. if(proc==IntPtr.Zero) {
  545. throw new ArgumentException("Can't find process with ID " + processId.ToString());
  546. }
  547. return(new Process(proc, processId));
  548. }
  549. [MonoTODO]
  550. public static Process GetProcessById(int processId, string machineName) {
  551. throw new NotImplementedException();
  552. }
  553. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  554. private extern static int[] GetProcesses_internal();
  555. public static Process[] GetProcesses() {
  556. int[] pids=GetProcesses_internal();
  557. ArrayList proclist=new ArrayList();
  558. for(int i=0; i<pids.Length; i++) {
  559. try {
  560. proclist.Add(GetProcessById(pids[i]));
  561. } catch (SystemException) {
  562. /* The process might exit
  563. * between
  564. * GetProcesses_internal and
  565. * GetProcessById
  566. */
  567. }
  568. }
  569. return((Process[])proclist.ToArray(typeof(Process)));
  570. }
  571. [MonoTODO]
  572. public static Process[] GetProcesses(string machineName) {
  573. throw new NotImplementedException();
  574. }
  575. public static Process[] GetProcessesByName(string processName) {
  576. Process[] procs=GetProcesses();
  577. ArrayList proclist=new ArrayList();
  578. for(int i=0; i<procs.Length; i++) {
  579. /* Ignore case */
  580. if(String.Compare(processName,
  581. procs[i].ProcessName,
  582. true)==0) {
  583. proclist.Add(procs[i]);
  584. }
  585. }
  586. return((Process[])proclist.ToArray(typeof(Process)));
  587. }
  588. [MonoTODO]
  589. public static Process[] GetProcessesByName(string processName, string machineName) {
  590. throw new NotImplementedException();
  591. }
  592. public void Kill ()
  593. {
  594. Close (1);
  595. }
  596. [MonoTODO]
  597. public static void LeaveDebugMode() {
  598. }
  599. [MonoTODO]
  600. public void Refresh() {
  601. }
  602. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  603. private extern static bool Start_internal(string appname,
  604. string cmdline,
  605. string dir,
  606. IntPtr stdin,
  607. IntPtr stdout,
  608. IntPtr stderr,
  609. ref ProcInfo proc_info);
  610. private static bool Start_common(ProcessStartInfo startInfo,
  611. Process process) {
  612. ProcInfo proc_info=new ProcInfo();
  613. IntPtr stdin_rd, stdin_wr;
  614. IntPtr stdout_rd, stdout_wr;
  615. IntPtr stderr_rd, stderr_wr;
  616. bool ret;
  617. if(startInfo.FileName == null || startInfo.FileName == "") {
  618. throw new InvalidOperationException("File name has not been set");
  619. }
  620. proc_info.useShellExecute = startInfo.UseShellExecute;
  621. if (proc_info.useShellExecute && (startInfo.RedirectStandardInput ||
  622. startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)) {
  623. throw new InvalidOperationException ("UseShellExecute must be false when " +
  624. "redirecting I/O.");
  625. }
  626. if (startInfo.HaveEnvVars) {
  627. if (startInfo.UseShellExecute)
  628. throw new InvalidOperationException ("UseShellExecute must be false in order " +
  629. "to use environment variables.");
  630. string [] strs = new string [startInfo.EnvironmentVariables.Count];
  631. startInfo.EnvironmentVariables.Keys.CopyTo (strs, 0);
  632. proc_info.envKeys = strs;
  633. strs = new string [startInfo.EnvironmentVariables.Count];
  634. startInfo.EnvironmentVariables.Values.CopyTo (strs, 0);
  635. proc_info.envValues = strs;
  636. }
  637. if(startInfo.RedirectStandardInput==true) {
  638. ret=MonoIO.CreatePipe(out stdin_rd,
  639. out stdin_wr);
  640. if (ret == false) {
  641. throw new IOException("Error creating standard input pipe");
  642. }
  643. } else {
  644. stdin_rd=MonoIO.ConsoleInput;
  645. /* This is required to stop the
  646. * &$*£ing stupid compiler moaning
  647. * that stdin_wr is unassigned, below.
  648. */
  649. stdin_wr=(IntPtr)0;
  650. }
  651. if(startInfo.RedirectStandardOutput==true) {
  652. ret=MonoIO.CreatePipe(out stdout_rd,
  653. out stdout_wr);
  654. if (ret == false) {
  655. throw new IOException("Error creating standard output pipe");
  656. }
  657. } else {
  658. stdout_rd=(IntPtr)0;
  659. stdout_wr=MonoIO.ConsoleOutput;
  660. }
  661. if(startInfo.RedirectStandardError==true) {
  662. ret=MonoIO.CreatePipe(out stderr_rd,
  663. out stderr_wr);
  664. if (ret == false) {
  665. throw new IOException("Error creating standard error pipe");
  666. }
  667. } else {
  668. stderr_rd=(IntPtr)0;
  669. stderr_wr=MonoIO.ConsoleError;
  670. }
  671. string cmdline;
  672. string appname;
  673. if (startInfo.UseShellExecute) {
  674. appname = null;
  675. string args = startInfo.Arguments;
  676. if (args == null || args.Trim () == "")
  677. cmdline = startInfo.FileName;
  678. else
  679. cmdline = startInfo.FileName + " " + startInfo.Arguments.Trim ();
  680. } else {
  681. appname = startInfo.FileName;
  682. // FIXME: There seems something wrong in process.c. We should not require extraneous command line
  683. if (Path.DirectorySeparatorChar == '\\')
  684. cmdline = appname + " " + startInfo.Arguments.Trim ();
  685. else
  686. cmdline = startInfo.Arguments.Trim ();
  687. }
  688. ret=Start_internal(appname,
  689. cmdline,
  690. startInfo.WorkingDirectory,
  691. stdin_rd, stdout_wr, stderr_wr,
  692. ref proc_info);
  693. MonoIOError error;
  694. if (!ret) {
  695. if (startInfo.RedirectStandardInput == true)
  696. MonoIO.Close (stdin_rd, out error);
  697. if (startInfo.RedirectStandardOutput == true)
  698. MonoIO.Close (stdout_wr, out error);
  699. if (startInfo.RedirectStandardError == true)
  700. MonoIO.Close (stderr_wr, out error);
  701. throw new Win32Exception (-proc_info.pid);
  702. }
  703. if (process.enableRaisingEvents && process.Exited != null) {
  704. WaitOrTimerCallback cb = new WaitOrTimerCallback (CBOnExit);
  705. ProcessWaitHandle h = new ProcessWaitHandle (proc_info.process_handle);
  706. ThreadPool.RegisterWaitForSingleObject (h, cb, process, -1, true);
  707. }
  708. process.process_handle=proc_info.process_handle;
  709. process.pid=proc_info.pid;
  710. if(startInfo.RedirectStandardInput==true) {
  711. MonoIO.Close(stdin_rd, out error);
  712. process.input_stream=new StreamWriter(new FileStream(stdin_wr, FileAccess.Write, true));
  713. process.input_stream.AutoFlush=true;
  714. }
  715. if(startInfo.RedirectStandardOutput==true) {
  716. MonoIO.Close(stdout_wr, out error);
  717. process.output_stream=new StreamReader(new FileStream(stdout_rd, FileAccess.Read, true));
  718. }
  719. if(startInfo.RedirectStandardError==true) {
  720. MonoIO.Close(stderr_wr, out error);
  721. process.error_stream=new StreamReader(new FileStream(stderr_rd, FileAccess.Read, true));
  722. }
  723. return(ret);
  724. }
  725. public bool Start() {
  726. bool ret;
  727. ret=Start_common(start_info, this);
  728. return(ret);
  729. }
  730. public static Process Start(ProcessStartInfo startInfo) {
  731. Process process=new Process();
  732. bool ret;
  733. ret=Start_common(startInfo, process);
  734. if(ret==true) {
  735. return(process);
  736. } else {
  737. return(null);
  738. }
  739. }
  740. public static Process Start(string fileName) {
  741. return Start(new ProcessStartInfo(fileName));
  742. }
  743. public static Process Start(string fileName,
  744. string arguments) {
  745. return Start(new ProcessStartInfo(fileName, arguments));
  746. }
  747. public override string ToString() {
  748. return(base.ToString() +
  749. " (" + this.ProcessName + ")");
  750. }
  751. /* Waits up to ms milliseconds for process 'handle' to
  752. * exit. ms can be <0 to mean wait forever.
  753. */
  754. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  755. private extern bool WaitForExit_internal(IntPtr handle,
  756. int ms);
  757. public void WaitForExit() {
  758. WaitForExit_internal(process_handle, -1);
  759. }
  760. public bool WaitForExit(int milliseconds) {
  761. if (milliseconds == int.MaxValue)
  762. milliseconds = -1;
  763. return WaitForExit_internal (process_handle, milliseconds);
  764. }
  765. [MonoTODO]
  766. public bool WaitForInputIdle() {
  767. return(false);
  768. }
  769. [MonoTODO]
  770. public bool WaitForInputIdle(int milliseconds) {
  771. return(false);
  772. }
  773. [Category ()]
  774. [MonitoringDescription ("Raised when this process exits.")]
  775. public event EventHandler Exited;
  776. // Closes the system process handle
  777. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  778. private extern void Process_free_internal(IntPtr handle);
  779. private bool disposed = false;
  780. protected override void Dispose(bool disposing) {
  781. // Check to see if Dispose has already been called.
  782. if(this.disposed == false) {
  783. this.disposed=true;
  784. // If this is a call to Dispose,
  785. // dispose all managed resources.
  786. if(disposing) {
  787. // Do stuff here
  788. }
  789. // Release unmanaged resources
  790. lock(this) {
  791. if(process_handle!=IntPtr.Zero) {
  792. Process_free_internal(process_handle);
  793. process_handle=IntPtr.Zero;
  794. }
  795. if (input_stream != null) {
  796. input_stream.Close();
  797. input_stream = null;
  798. }
  799. if (output_stream != null) {
  800. output_stream.Close();
  801. output_stream = null;
  802. }
  803. if (error_stream != null) {
  804. error_stream.Close();
  805. error_stream = null;
  806. }
  807. }
  808. }
  809. base.Dispose (disposing);
  810. }
  811. static void CBOnExit (object state, bool unused)
  812. {
  813. Process p = (Process) state;
  814. p.OnExited ();
  815. }
  816. protected void OnExited()
  817. {
  818. if (Exited == null)
  819. return;
  820. if (synchronizingObject == null) {
  821. Exited (this, EventArgs.Empty);
  822. return;
  823. }
  824. object [] args = new object [] {this, EventArgs.Empty};
  825. synchronizingObject.BeginInvoke (Exited, args);
  826. }
  827. class ProcessWaitHandle : WaitHandle
  828. {
  829. public ProcessWaitHandle (IntPtr handle)
  830. {
  831. Handle = handle;
  832. }
  833. protected override void Dispose (bool explicitDisposing)
  834. {
  835. // Do nothing, we don't own the handle and we won't close it.
  836. }
  837. }
  838. }
  839. }