创build一个可停止的Linux服务

我试图运行一个NodeJS应用程序作为一个Linux服务。 我在/etc/init.d文件夹下创build了一个服务文件,内容如下:

 #!/bin/bash # chkconfig: 2345 20 80 # description: Description comes here.... # Source function library. . /etc/init.d/functions start() { # code to start app comes here # example: daemon program_name & /usr/bin/node /home/folder/nodeapp.js & echo "Service started">&2 } stop() { # code to stop app comes here # example: killproc program_name killproc /usr/bin/node echo "Service stopped">&2 } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) # code to check status of app comes here # example: status program_name ;; *) echo "Usage: $0 {start|stop|status|restart}" esac 

这是它运行的JS文件:

 var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end("aa1"); }).listen(8081); 

我可以开始这项服务,它的工作很好。 问题是我不知道如何正确地阻止它。 上面的停止function实际上会杀死节点进程(node.exe),所有节点应用程序都会自动停止。 我只需要停止我的nodeapp.js。

所以我需要这样的东西:

 stop() { # code to stop app comes here # example: killproc program_name killproc /usr/bin/node /home/folder/nodeapp.js echo "Service stopped">&2 } 

但是,当然,这是行不通的。

顺便说一下,请不要使用systemctl或者其他新的东西。 我知道这很容易,但我必须使用旧版本的CentOS。

这样做的经典方法是在启动后直接将进程ID号写入文件( echo $! > /var/run/myapp.pid )。 要停止它,重新读取文件并kill PID。