LoginSignup
4
5

More than 5 years have passed since last update.

C# コンソールから起動した別プロセスが時間内に終了しなかったらプロセスを殺す

Last updated at Posted at 2016-02-03

コンソールアプリで起動した別プロセスを殺す

作ろうと思った理由

コンソールから起動した別プロセスがダイアログを表示したまま、プロセスが終わるまで待っていてメインプロセスがフリーズしてしまった。
一定時間起動した別プロセスが終了しなかったら殺したい。

イメージ図

20160202_005.png

ソースコード

メモ帳を起動してから、1分以内に終了しなかったら、メモ帳を殺して終了する

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleProcessWaitEnd
{
    class Program
    {
        private const int MAX_SECCONDS = 10 * 1000;

        static void Main(string[] args)
        {
            ProcessStartInfo psiNotepad = new ProcessStartInfo();
            psiNotepad.FileName = @"notepad";
            Process psNotepad = System.Diagnostics.Process.Start(psiNotepad);

            if(!psNotepad.WaitForExit(MAX_SECCONDS))
            {
                psNotepad.Kill();
            }

        }
    }
}

何分間か動かなかったら時々警告を出すようにするならThreadにする必要がある。

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace ConsoleThread
{
    class Program
    {
        private const int MAX_SECCONDS = 60;
        static private int timerCount = 0;
        static private bool isSuccess = false;

        static private Process psNotepad;

        static void Main(string[] args)
        {
            Thread thexe = new Thread(new ThreadStart(ThreadExe));

            thexe.Start();

            while (true)
            {
                if (isSuccess)
                {
                    Console.WriteLine("OK");
                    break;
                }

                if (timerCount < MAX_SECCONDS)
                {
                    Thread.Sleep(1000);
                    timerCount++;
                }

                else
                {
                    Console.WriteLine("NG");
                    psNotepad.Kill();
                    thexe.Abort();
                    break;
                }
            }
            Console.ReadKey();
        }

        private static void ThreadExe()
        {
            ProcessStartInfo psiNotepad = new ProcessStartInfo();
            psiNotepad.FileName = @"notepad";
            psNotepad = System.Diagnostics.Process.Start(psiNotepad);
            psNotepad.WaitForExit();
            isSuccess = true;
        }
    }
}

git

ConsoleThread

4
5
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5