Skip to content

Commit

Permalink
Start時にRUNNING.PID が存在する場合、そのProcessIDが実行中であれば終了、実行されていなければRUNNING.PI…
Browse files Browse the repository at this point in the history
…Dを削除して継続
  • Loading branch information
XenonAbe committed Sep 13, 2019
1 parent cc0901a commit dbe01c8
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion PlayService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ public PlayService()
protected override void OnStart(string[] args)
{
if (File.Exists(pidfilePath)) {
throw new ApplicationException($"This application is already running (Or delete {pidfilePath} file)");
if (IsValidPidFile(out int pid))
throw new ApplicationException($"This application is already running (ProcessID={pid})");

EventLog.WriteEntry($"Delete last {Path.GetFileName(pidfilePath)}. {(pid >=0 ? $"(ProcessID={pid})" : "")}", EventLogEntryType.Warning);
File.Delete(pidfilePath);
}

RequestAdditionalTime(StartTimeout);
Expand Down Expand Up @@ -253,6 +257,27 @@ private void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
e.Cancel = true;
}

private bool IsValidPidFile(out int pid)
{
pid = -1;
using (var r = new StreamReader(pidfilePath, new UTF8Encoding(false))) {
var line = r.ReadLine()?.Trim();
if (string.IsNullOrEmpty(line))
return false;
if (!int.TryParse(line, out pid))
return false;
try {
using (Process.GetProcessById(pid))
{
}
} catch (ArgumentException) {
return false;
}
}

return true;
}

private string pidfilePath
{
get
Expand Down

0 comments on commit dbe01c8

Please sign in to comment.