linux - 如果他们的 etime 大于 X 时间量,我如何终止特定进程?

标签 linux bash shell awk sed

我正在尝试获取 ps axo uname,pid,etime,time,cmd 的输出并使用 etime>=10 终止所有相关进程

我只需要为存储在单独文件 users.txt 中的特定用户杀死 pids

基本上,我想查看我所有的列,我想找到属于特定用户的所有 php{5,54} 进程,存储在一个文件中,如果执行时间超过十分钟,则终止这些进程。 (不需要 kill -9)

示例 ps 输出:

username   574        01:37 00:00:18 /ramdisk/bin/php54 /home/username/public_html/index.php
usernum2  1367        10:28 00:00:16 /ramdisk/bin/php54 /home/usernum2/public_html/index.php
user3     3971   1-04:17:31 00:00:14 /ramdisk/bin/php54 /home/user3/public_html/index.php
usernum4  9130     14:05:32 00:00:29 /ramdisk/bin/php54 /home/usernum4/public_html/index.php
username  9189   1-01:31:12 00:00:25 /ramdisk/bin/php54 /home/username/public_html/index.php

我的想法是将 ps 输出放入一个文件(例如 procs.txt),然后 grep 遍历该文件。 例如:

ps axo uname,pid,etim,time,cmd | grep 'php5' |三通 procs.txt

我可以有两行:第一行说如果第 3 列超过 5 个字符会杀死 pid,这很容易,然后另一行有类似下面的内容,但这并没有给我留下相关的 pid,所以我不能杀了他们:

for i in $( cat users.txt );做 grep $i procs.txt | awk '{print $3}' | awk -F: '{print $(NF-1)}' | awk '$1>=10{print $1}';完成

最佳答案

以下是bash中的解决方案.

查找匹配 php5 的所有进程或 php54 ,对于文件中的用户,我会使用 U ps 的选项和 egrep :

ps xo uname,pid,etim,time,cmd U"$(echo $(< users.txt))" | egrep '/php54? '

U选项将只显示属于提供的用户列表的进程。 <cat 的内置 shell , 以及 echo 的使用将文件条目展平为一行,ps命令期望。

'/php54? '表示 4是可选的,末尾的空格确保它不匹配(例如)php52 . egrep使用正则表达式,所以它允许使用 ?元字符。

然后可以使用 while read 逐行处理此命令的输出。 :

ps xo uname,pid,etim,time,cmd U"$(echo $(< users.txt))" | egrep '/php54? ' \
| while read a
  do cols=($a)
     elapsed=${cols[2]}
     if [ ${#elapsed} -gt 5 ]
     then kill ${cols[1]}
     elif [ ${elapsed%%:*} -gt 9 ]
     then kill ${cols[1]}
     fi
  done

cols获取一个数组赋值,拆分行 a在空白边界上。用户在 cols[0] , PID 在 cols[1] , ELAPSED 在 cols[2] 中.如果 ELAPSED 的字符串长度大于 5(表示经过至少一个小时),或者如果 minutes 字段大于 9(经过至少 10 分钟),则 PID 将被杀死。 %%扩展运算符进行最长匹​​配后缀删除。

解决方案可以通过 read 压缩- 直接进入相关领域:

ps xo uname,pid,etim,time,cmd U"$(echo $(< users.txt))" | egrep '/php54? ' \
| while read user pid elapsed rest_of_line
  do if [ ${#elapsed} -gt 5 ]
     then kill $pid
     elif [ ${elapsed%%:*} -gt 9 ]
     then kill $pid
     fi
  done

关于linux - 如果他们的 etime 大于 X 时间量,我如何终止特定进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916106/

相关文章:

python - 这可能是 Anaconda 2.5.0 环境中 scipy.sparse.linalg.eigs 函数中的错误吗?

linux - 如何使用 shell 脚本计算每行中的选项卡数?

Linux 狂欢 : Move multiple different files into same directory

linux - 在 Linux 上的进程之间共享套接字

linux - Bash - 自解压脚本错误

bash - 将 zenity 的输出分配给变量

linux - Shell 脚本 while 只循环一次

linux - Linux上远程执行脚本

bash - 如何不敏感地检查文件相似度大小写

c - 错误 : request for member ‘sin_addr’ in something not a structure or union