从同一个脚本中终止其他bash守护进程

问题描述:

我有一段时间试图编写一个“终止所有其他守护进程”函数以便在bash守护进程中使用。我永远不会想要一次运行多个守护进程。有什么建议么?这是我有:从同一个脚本中终止其他bash守护进程

#!/bin/bash 

    doService(){ 
     while 
     do 
     something 
     sleep 15 
     done 
    } 

    killOthers(){ 
     otherprocess=`ps ux | awk '/BashScriptName/ && !/awk/ {print $2}'| grep -Ev $$` 

     WriteLogLine "Checking for running daemons." 

     if [ "$otherprocess" != "" ]; then 
      WriteLogLine "There are other daemons running, killing all others." 
      VAR=`echo "$otherprocess" |grep -Ev $$| sed 's/^/kill /'` 
      `$VAR` 
     else 
      WriteLogLine "There are no daemons running."  
     fi 
     } 


     killOthers 
     doService 

它的作品有些时候,它不是别人。几乎没有任何一致。

如果您runserviceunderrunit - 服务不能进叉的背景 - 你必须保证恰好有运行它的一个实例。如果服务没有运行,或者它退出或崩溃,runit会启动该服务,如果你问,请停止服务,并保留一个pid文件。

+0

嗯,不幸的是我没有runit。我正在运行一个非devloper(没有xcode工具)的vanilla OSX安装。 – 2010-01-28 00:28:09

+0

它可能打包在某个地方,但我会让osx用户提供一个链接或等价物。 – Tobu 2010-01-28 00:40:58

+0

编辑了我的原始文章以反映这一点:此Apple Dev文档看起来很有前途:http://developer.apple.com/mac/library/DOCUMENTATION/MacOSX/Conceptual/BPSystemStartup/Articles/StartupItems。html – monojohnny 2010-01-29 08:52:05

你可以在这里尝试旧的'锁定文件'技巧吗?测试一个文件:如果它不存在,创建它然后启动;否则退出。

像:

#!/bin/bash 
LOCKFILE=/TMP/lockfile 
if [ -f "$LOCKFILE" ]; then 
     echo "Lockfile detected, exiting..." 
     exit 1 
fi 
touch $LOCKFILE 
while : 
do 
     sleep 30 
done 
rm $LOCKFILE # assuming an exit point here, probably want a 'trap'-based thing here. 

的缺点是,你必须锁定文件清理不时,如果一个孤儿被抛在后面。

您可以将它转换为'rc'(或S */K *脚本?),以便您可以在inittab中指定'once'(或等效的方法 - 不确定在MacOS上)?

喜欢这里所描述的那样:

http://aplawrence.com/Unixart/startup.html

编辑:

可能这苹果文档可能有助于在这里:​​

http://developer.apple.com/mac/library/DOCUMENTATION/MacOSX/Conceptual/BPSystemStartup/Articles/StartupItems.html

+0

我想让最近调用的守护进程保持活动状态。我不确定这个解决方案是否适合我的计划。 – 2010-01-27 19:48:39

你已经消除当前进程ID使用grep -v,所以当你发出时没有理由再次这样做e kill。也没有理由在变量中构建kill。只要做到:

kill $otherprocess 

但是,为什么不直接使用:

pkill -v $$ BashScriptName 

pkill -v $$ $0 

没有任何的grep。

然后,你可以这样做:

if [[ $? ]] 
then 
    WriteLogLine "Other daemons killed." 
else 
    WriteLogLine "There are no daemons running." 
fi 
+0

我没有pkill选项... kill $ otherprocess似乎也不工作。 – 2010-01-27 19:47:37