Shell 脚本本身杀死自己的运行脚本进程 ID



我正在使用以下命令来获取pid。"A"是应用程序名称,用作参数。我像 ./stop A 一样运行我的脚本

PID=`ps -ef | grep A| grep -v grep | awk '{print$2}'`

这也是捕获"/bin/ksh ./stop A"进程。但我不想要。我只想捕获"A"的过程,而不是我在 PID 中的脚本过程/

我的脚本下有以下 kill 命令,它正在杀死我正在运行的脚本:(

kill -9 $PID

它也在杀死/bin/ksh ./stop A本身的pid,脚本在这一点上被停止了。

这是针对 AIX 的。如何避免杀死脚本本身。

注意:当我使用相同的脚本来完成相同的工作但不传递参数时,它进展顺利。我相信很明显,因为将参数传递给脚本正在创建其他 pid,并且对于同一应用程序,它会执行 grep 和杀戮。

如果停止 A 是你所说的杀戮的脚本,你可以这样做

for p in $PID
do
   test $p -ne $$ && kill -9 $p
done

请注意,所有其他包含 A 的进程仍处于危险之中,您可以添加 grep -w A 以限制为 A 是单个单词的进程

编辑或不编辑循环

kill -9 $( ps -ef|grep -w A |grep -v -w $$ | grep -v grep | awk '{print $2}' )

(grep -v grep 在这里应该是不必要的)

有一个名为pidof的实用程序,它列出了具有给定名称的程序实例的PID。它在大多数 Linux 机器上都可用,所以也许它在 AIX 上也可用?

从手册页:

Pidof finds the process id's (pids) of the named programs.
It prints those id's on the standard output.

也:

When pidof is invoked with a full pathname to the program
it should find the pid of, it is reasonably safe.
Otherwise it is possible that  it  returns  pids  of running
programs  that  happen to have the same name as the program
you're after but are actually other programs.

最新更新