ProcessLocker.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Diagnostics;
  7. namespace SuperSocket.SocketEngine
  8. {
  9. class ProcessLocker
  10. {
  11. private string m_LockFilePath;
  12. public ProcessLocker(string workDir, string lockFileName)
  13. {
  14. m_LockFilePath = Path.Combine(workDir, lockFileName);
  15. }
  16. public Process GetLockedProcess()
  17. {
  18. if (!File.Exists(m_LockFilePath))
  19. return null;
  20. int processId;
  21. if (!int.TryParse(File.ReadAllText(m_LockFilePath), out processId))
  22. {
  23. File.Delete(m_LockFilePath);
  24. return null;
  25. }
  26. try
  27. {
  28. return Process.GetProcessById(processId);
  29. }
  30. catch
  31. {
  32. File.Delete(m_LockFilePath);
  33. return null;
  34. }
  35. }
  36. public void SaveLock(Process process)
  37. {
  38. File.WriteAllText(m_LockFilePath, process.Id.ToString());
  39. }
  40. public void CleanLock()
  41. {
  42. if (File.Exists(m_LockFilePath))
  43. File.Delete(m_LockFilePath);
  44. }
  45. ~ProcessLocker()
  46. {
  47. CleanLock();
  48. }
  49. }
  50. }