kill long running linux processes

How to Kill Process Running Longer Than Specific Time

Sometimes you may find that certain long running processes have become non-responsive, or are consuming too much system resources. In such cases, you may need to kill these processes. In this article, we will learn how to kill process running longer than specific time.


How to Kill Process Running Longer Than Specific Time

We will need to use multiple commands to find and kill process longer than specific time. First, we will kill process running longer than 5 minutes, that is, 300 seconds.


1. List Process Running Times

First, we will use ps command to get a list of all processes with their Name, PID, Running Time.

$ ps -eo comm,pid,etimes


2. Find Long Running Processes

Next, we will pass the above output to awk command to get only those processes that are running for more than 300 seconds. In the above output, the third column is the number of seconds each process has been running for.

ps -eo comm,pid,etimes | awk '/^procname/ {if ($3 > 300) { print $2}}'

In the above command, awk goes through the output of ps command to check if the value in 3rd column (duration) is more than 300. If so, then it prints the 2nd column (PID) of that process.


3. Kill Long Running Processes

Now that we have list of PIDs of processes running longer than given duration, we can issue kill commands to kill those processes.

$ kill -9 $(ps -eo comm,pid,etimes | awk '/^procname/ {if ($3 > 300) { print $2}}')

Similarly, you can find and kill processes running longer than 3 hours or even 24 hours, with the following commands.

## kill processes running longer than 3 hours
$ kill -9 $(ps -eo comm,pid,etimes | awk '/^procname/ {if ($3 > 10800) { print $2}}')

## kill processes running longer than 24 hours
$ kill -9 $(ps -eo comm,pid,etimes | awk '/^procname/ {if ($3 > 86400) { print $2}}')

In this article, we have learnt how to kill processes running for than specific time in Linux. You can use these commands on almost every Linux distribution.

Also read:

How to Split Tar into Multiple Files
How to Configure Samba Server in RHEL, CentOS
How to Rename All Files to Lowercase or Uppercase in Linux
How to Find Index of Item in Python List
How to Redirect Using JavaScript

Leave a Reply

Your email address will not be published.