【问题标题】:Bash : Find parent process id of a script from another script and take some actionsBash:从另一个脚本中找到一个脚本的父进程ID并采取一些行动
【发布时间】:2021-03-23 12:14:52
【问题描述】:

我有一个脚本 workingScript.sh。我还有另一个脚本,称为 monitorscript.sh,我想用它来监控 workingScript.sh 的 processid 活动。

我想确保如果有任何 wc/cat 除了从 17506(workingScript.sh 的父进程)生成的进程 id 之外,它应该被 monitorscript.sh 杀死

ps aux|grep "workingScript*"
svc.test+ 25896  0.0  0.0 112812   984 pts/3    S+   01:15   0:00 grep --color=auto workingScript*
svc.test+ 17506  0.0  0.0 113288  1072 ?        S    Mar18   0:00 sh workingScript.sh
svc.test+ 17510  0.0  0.0 113412   868 ?        S    Mar18   0:03 sh workingScript.sh

workingScript.sh 父进程 id 的进程树如下所示。

pstree -p 17506
    sh(17506)─┬─cat(17509)
      └─sh(17510)─wc(17569)

因此,在任何时候,如果任何 wc/cat 进程 id 与 workingScript.sh 创建的进程 id 不同(在本例中为 17509/17569,根据上述进程树),它应该被杀死

我们可以使用PPID来获取相同脚本的进程ID,但是我们如何获取不同脚本的进程ID以及不同脚本的相关子进程

有人可以帮我吗?

【问题讨论】:

  • 将“不同脚本”的 PPID 回显到脚本内的文件中。然后,您可以从另一个进程引用该文件和 PID。
  • 总的来说,it should be killed by monitorscript.sh 这是错误的做法。我并没有真正理解重点——如果cat 足够短,那么monitorscript.sh 甚至都不会注意到它。 how can we get for different script and related child processes for a different script 正如你所展示的,ps aux | grep 写成 pgreppstree 更好。您在帖子中使用了它们 - 所以在您的脚本中使用它们。
  • @kamilCuk 实际上,为了演示,我提到了 cat ,实际上是我想杀死的 inotifywait 进程。所以我同意你的观点,即为什么有人会试图杀死一个 cat 进程,但实际上它不是那样的

标签: linux bash shell unix process


【解决方案1】:

运行 workingScript.shLD_PRELOAD 并覆盖 exec*() 调用。然后在这些exec*() 调用中检查命令是否解析为wccat 可执行文件。如果是,raise 如果你愿意,可以发出一些杀戮信号。记得导出LD_PRELOAD,这样子进程exec*()s 也会被覆盖。


如果您希望定期检查脚本中的进程,那么只需找到 pid 并杀死它们:

pid=$(pgrep workingScript.sh)
while sleep "$polling_period"; then
   # ex. killing cat
   pkill -P "$pid" cat
fi

【讨论】:

  • pid=$(pgrep workingScript.sh) 这没有给出任何输出..是因为我必须使用 LD_PRELOAD 运行 workingScript.sh 并覆盖 exec*() 调用。没有这个 LD_PRELOAD 的任何解决方案?
  • Is it because I have to run 不,这很可能是因为匹配表达式错误。检查进程的名称并正确匹配它。 Any solution without this LD_PRELOAD?您可以附加调试器或在进程上运行strace -ff(或ptrace())以获取执行调用。
猜你喜欢
  • 2023-01-13
  • 2014-11-18
  • 2013-06-17
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多