2017-08-11 30 views
1

我试图运行一个NodeJS应用程序作为Linux服务。我创建了/etc/init.d文件夹下的服务文件与下面的内容:创建可停止的Linux服务

#!/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); 

我可以启动该服务,它是伟大的工作。问题是我不知道如何正确地阻止它。上面的停止功能实际上会杀死节点进程(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。

回答

0

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