【问题标题】:Unable to find a shell script that runs in the background via pgrep or ps -grep无法通过 pgrep 或 ps -grep 找到在后台运行的 shell 脚本
【发布时间】:2019-11-19 08:52:55
【问题描述】:

我有一个名为 toto.sh 的文件,文件内容是:

#!/bin/sh
for i in $(seq 1 100); 
do
   echo "CREATE TABLE test_$i (id NUMBER NOT NULL);
   ! sleep 10
   select * from test_$i;
   ! sleep 10
   DROP TABLE test_$i;" | sqlplus system/mypassword &
done

我执行 bash 脚本:

./toto.sh

现在我正在尝试像这样搜索过程:

pgrep -f toto.sh
ps -ef | grep toto.sh
ps aux | grep toto.sh

我没有得到相关结果:

root     24494 15043  0 10:47 pts/5    00:00:00 grep toto.sh

但是,我可以通过 pgrep 等看到通过脚本启动的 sleep 和 sqlplus 进程,

我在这里做错了什么?

【问题讨论】:

  • 在你运行 pgrep 之前,脚本可能会死掉,留下孤立的 sqlplus 实例
  • 脚本怎么会在休眠时死掉?我们使用更长的睡眠时间,但仍然存在同样的问题
  • echo 回显后退出,toto.sh 向后台发送100个进程后退出,只有sqlpluses在休眠后保持存活
  • 杀死是什么意思?在你运行它的那一刻它就已经死了
  • 杀死 sqlplus 进程:echo ... | sqlplus system/mypassword & echo $! >>pids.txt。稍后:kill $(<pids)

标签: linux bash shell process long-running-processes


【解决方案1】:

当你想显示 toto.sh 时,让它保持活跃。以wait 结束脚本,等待所有孩子。

#!/bin/bash
for i in $(seq 1 100); 
do
   echo "CREATE TABLE test_$i (id NUMBER NOT NULL);
   ! sleep 10
   select * from test_$i;
   ! sleep 10
   DROP TABLE test_$i;" | sqlplus system/mypassword &
done
wait

另一种方法是在循环中添加一个睡眠命令(我在 10 次迭代后睡眠 1 秒):

#!/bin/bash
for i in $(seq 1 100); 
do
   echo "CREATE TABLE test_$i (id NUMBER NOT NULL);
   ! sleep 10
   select * from test_$i;
   ! sleep 10
   DROP TABLE test_$i;" | sqlplus system/mypassword &
   ((i%10==0)) && { echo "i=$i"; sleep 1; }
done

【讨论】:

  • 但是,这样sleeps 不会死,即使toto.sh 被杀死
  • @oguzismail 杀死进程不是问题的一部分。我会删除睡眠命令sqlplus,数据库不需要它们。该脚本是一个示例,创建和删除表没有功能结果。
  • 哦,好吧,我没有意识到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多