我实际上想要实现的是:
我试图让一个自定义的守护进程在使用SysVinit的系统上工作。 我已经有引导程序/etc/init.d/xyz脚本,它调用我的守护进程,但它不会自动将它放在后台。 这类似于nginx这样的服务:二进制背景本身 – 也就是说,不是/etc/init.d/nginx脚本负责守护进程,所以如果直接运行/opt/nginx/sbin/nginx也会遇到守护进程/后台执行。
问题
我的问题是,使用我当前的方法,该守护进程不会终止与父进程(这是什么被终止时,你叫service xyz stop )。
我正在使用运行daemon.sh &脚本的父launcher.sh脚本。 然而,当我杀死launcher.sh , daemon.sh继续运行,尽pipe我尽了最大的努力与trap (它从来没有被称为):
– > launcher.sh
#!/bin/bash function shutdown { # Get our process group id PGID=$(ps -o pgid= $$ | grep -o [0-9]*) echo THIS NEVER GETS CALLED! # Kill process group in a new process group setsid kill -- -$$ exit 0 } trap "shutdown" SIGTERM # Run daemon in background ./daemon.sh &
– > daemon.sh
#!/bin/bash while true do sleep 1 done
运行并杀死:
./launcher.sh <get PID for launcher> kill -TERM 123 # PID of launcher.sh... which _is_ still running and has its own PID.
结果: daemon.sh仍在运行, shutdownfunction永远不会被调用 – 我已经通过在函数体中放置一个echo here证实这一点。
有任何想法吗?
编辑: launcher.sh脚本正在使用daemon launcher.sh ,其中daemon是由亚马逊Linux的init.d/functions文件提供的init.d/functions (请参阅: http : //gist.github.com/ljwagerfield/ab4aed16878dd9a8241b14bc1501392 F)。
只有脚本运行时, trap命令才会起作用。
通常的做法是,当守护进程被分离出来时,它将PID写入一个文件中。 然后init脚本使用该文件来确定要杀死的进程,或者调用启动脚本来终止进程。
一审:
launcher.sh:
/path/to/daemon.sh & echo "$!" > /var/run/xyz.pid
/etc/init.d/xyz一个简单而有点天真的版本:
# ... pull in functions or sysconfig files ... start() { # ... do whatever is needed to set things up to start ... /path/to/launcher.sh } stop() { # ... do whatever is needed to set things up to stop ... kill `cat /var/run/xyz.pid` } # ... other functions ...
一个非天真的启动脚本将取决于你正在运行的是哪个版本的linux; 我build议看看/etc/init.d中的其他例子,看看他们是如何做到这一点的。
这对我来说没有任何意义,为什么你要有两个脚本来做这个。 你可以在你的初始化脚本中调用daemon.sh & ? 或者也许你可以使用daemon命令。
NAME daemon - turns other processes into daemons SYNOPSIS usage: daemon [options] [--] [cmd arg...]
如果您需要使用陷阱,也许您可以在daemon.sh使用它来进行干净closures。 很难说这些是你真正的脚本还是只是例子。
launcher.sh部分问题是它退出了,没有任何东西在运行,所以你不能杀死它 – 它已经不存在了。 我不只是这样说,我实际上testing了你的脚本,以确保在我回答之前。 看到我的意见添加到您的脚本。
#!/bin/bash function shutdown { # Get our process group id PGID=$(ps -o pgid= $$ | grep -o [0-9]*) echo THIS NEVER GETS CALLED! # Kill process group in a new process group setsid kill -- -$$ exit 0 } trap "shutdown" SIGTERM # Run daemon in background *** script keeps running *** ./daemon.sh & # It exits here echo "Exiting... bye!"