Java教程

【Ubuntu】shell监控进程定时杀死进程

本文主要是介绍【Ubuntu】shell监控进程定时杀死进程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

功能描述

Ubuntu系统下spring项目,调用命令行执行相关指令,在执行到某个函数时会调起一个窗口,此时进程停滞,必须手动关闭该窗口才能使进程继续执行,现在的需求是想自动关闭该窗口。

思路

使用shell脚本监控该进程,当检测到该进程时就使用kill命令杀死该进程。

shell

教程:Shell教程

#!/bin/bash
echo `date` # 输出当前时间,注意这里用的是键盘右上角的~~键
while true
do
  #  pid=&(pgrep Viewer)
  #  count=&(ps -e | grep Viewer | wc -l)
  count=`ps -e | grep Viewer | wc -l` #统计该进程的数量,可能会同时开启多个
#  echo "now have $count process"
  if [[ $count != 0 ]] # 进程数不为0也就是当前存在该进程时
  then
      echo "now have $count Viewer process"
      echo "`date` process Viewer is running" >> /home/smartcity/Desktop/Viewer.log #输出log
      sleep 20 # 等待20s后
      killall Viewer # 杀死当前进程名的所有进程,Viewer为进程名
  fi
  sleep 2 # 每2秒检测一次,时间可以长一些
done

几个进程相关的命令

参考博客:Linux下查看进程和端口信息

ps -e # 查看所有进程
pgrep process_name # 查看进程的pid
ps -ef | grep tomcat # 查看进程id
ps -aux | grep process_name #查看内存占用情况及pid
ps -e | grep process_name | wc -l # 统计进程数量
top -d 1 -p pid [,pid …] #设置为delay 1s,默认是delay 3s

kill:[Linux] killall 、kill 、pkill 命令详解

执行结果

在这里插入图片描述
参考博客:
Ubuntu Linux下定时监测MySQL进程终止时自动重启的方法
Ubuntu14 定时查询任务进程存活状态以及定时杀死进程和重启

这篇关于【Ubuntu】shell监控进程定时杀死进程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!