---
title: "Monitor a process, if  have run for more than 2 mins,kill it."
author: "Ihavegotyou"
date: "2016-08-05T18:01:28Z"
tags: []
categories: ["操作系统"]
slug: "monitor-a-process-if-have-run-for-more-than-2-mins-kill-it"
draft: false
lastmod: "2016-08-05T18:01:28Z"
id: 2315843
url: "https://ucstudio.iteye.com/blog/2315843"
---

```
#!/bin/bash -l
process_name='phantomjs'
long_term=1
pids=` ps -ef | grep -i "$process_name"  | grep -v 'grep' | awk '{print $2;}'`

if [ "$pids" == "" ]; then
   echo "no phantomjs running" >/dev/null
   exit 0
fi


for pid in $pids; do
  echo $pid
  etimes_min=` ps -p $pid -o etime=|awk -F":" '{print($(NF-1))}'`
  etimes_min=`echo $etimes_min | sed 's/^0//'`
  echo $etimes_min,$long_term
  if [ "$etimes_min" -gt "$long_term" ]; then
        kill -9 $pid >/dev/null
        timestamp=`date '+%Y%m%d %H:%M'`
        echo "$timestamp: killed $pid for $process_name, for it took more than 2 minus" >> "kill-long-term-phantomjs-processes.log"
  fi
done

```