LoginSignup
0
1

More than 5 years have passed since last update.

負荷のかかっているプロセスを削除する

Last updated at Posted at 2015-06-23

はじめに

時々暴走するプロセスのバグが修正されないので、負荷90%以上のタスクをバシっとKillするプログラムを作成しました。

プロセス名とインスタンス名

CPU負荷を調べるには、インスタンス名に変換する必要があります。それについては詳細は以下のエントリーで

判定条件について

hProcess.Responding = false で無応答タスクの判定ができるのですが、リモートからのコード実行やスケジュールタスクのようにバックグラウンドで実行する場合には正しくRespondingが返ってこないので、CPU負荷を条件として入れてあります。

コード

Module1.vb

    Sub TaskKill()
        Dim pc As New System.Diagnostics.PerformanceCounter()
        pc.CategoryName = "Process"
        pc.CounterName = "% Processor Time"

        Dim hProcesses As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcesses()
        For Each hProcess As System.Diagnostics.Process In hProcesses
                pc.InstanceName = LookupInstanceName(hProcess.Id)
                pc.NextValue()
                System.Threading.Thread.Sleep(1000)
                Dim cpuVal = Val(pc.NextValue.ToString)
                If cpuVal > 90 Then
                    hProcess.Kill()
                End If
        Next hProcess
    End Sub

      ' プロセスID→インスタンス名変換
    Function LookupInstanceName(pid) As String
        LookupInstanceName = ""
        Dim category = New PerformanceCounterCategory("Process")
        Dim instances = category.GetInstanceNames
        For Each instance In instances
            Dim c = New PerformanceCounter("Process", "ID Process", instance)
            If (pid = c.RawValue) Then
                LookupInstanceName = instance.ToString
                Return LookupInstanceName
            End If
        Next
        Return LookupInstanceName
    End Function

参考

ぶつぶつ

インスタンス名探索が繰り返し行われているので、配列を返すような関数としておいたほうが良いので書き直す予定です。

0
1
0

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
0
1