Skip to content

Instantly share code, notes, and snippets.

@smallpine
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smallpine/5401acb6ac925f0618c8 to your computer and use it in GitHub Desktop.
Save smallpine/5401acb6ac925f0618c8 to your computer and use it in GitHub Desktop.
Console Application with Kill switch
internal class Program
{
private const string MUTEX_NAME = "Global\\__KILL_SWITCH__";
private static Semaphore StopSignal;
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
internal static void Main(string[] args)
{
// コマンドライン引数に「/KILL」が指定されたときは、先に起動しているプロセスを終了させます。
if (args.Length > 0 && "/KILL".Equals(args[0].ToUpper()))
{
Logger.InfoFormat("/KILL パラメータ付で実行されました。実行中のプロセスを終了させます");
try
{
StopAnotherProcess();
}
catch (Exception ex)
{
Logger.Error("/KILL 処理が異常終了しました", ex);
}
return;
}
using (Program.StopSignal = new Semaphore(1, 1, MUTEX_NAME))
{
// 二重起動チェック
if (Program.StopSignal.WaitOne(0) == false)
{
Logger.Error("既に起動しています");
return;
}
// 別スレッドで主処理を
var app = new MainProcess();
app.Run();
// セマフォが解放されるまで待機
Program.StopSignal.WaitOne();
Logger.Info("Incoming KILL message.");
app.Stop();
}
}
private static void KillAnotherProcess()
{
using (Program.StopSignal = Semaphore.OpenExisting(MUTEX_NAME))
{
Program.StopSignal.Release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment