我想在启动时启动我的 Node js 应用程序。因此我从 Systemd 启动一个服务:
[Unit]
Description=Node.js server
After=network.target
[Service]
ExecStart=/usr/bin/node /var/www/Raspberry-Pi-Status/js/server.js
Restart = always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-server
Environment=NODE_ENV=production PORT=8000
Environment=PYTHONPATH=/usr/bin/python
[INSTALL]
WantedBy=multi-user.target
server.js 看起来像这样:
var util = require('util'),
spawn = require('child_process').spawn,
py = spawn('python',['temperature.py'],{detached: true});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'monitor',
password : 'password',
database : 'temps'});
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
sys = require('util'),
exec = require('child_process').exec,
child;
// Listen on port 8000
app.listen(8000);
// If all goes well when you open the browser, load the index.html file
function handler(req, res) {
fs.readFile(__dirname+'/../index.html', function(err, data) {
if (err) {
// If no error, send an error message 500
console.log(err);
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
py.stdout.on('data', function(data){
console.log('testing');
date = new Date().getTime();
temp = parseFloat(data);
io.sockets.emit('temperatureUpdate',date,temp);
});
// When we open the browser establish a connection to socket.io.
// Every 5 seconds to send the graph a new value.
io.sockets.on('connection', function(socket) {
console.log('user connected');
});
node.js 应用程序应启动一个读取温度传感器的 Python 脚本。当我通过控制台启动 node.js 时,一切正常。但是,当我从 Systemd 启动时,不会生成 python 脚本。 那里出了什么问题?我错过了什么吗?
提前致谢 亚历山大
最佳答案
问题可能是手动运行与 systemd 运行时当前工作目录存在差异。使用的 spawn
调用是 documented默认继承当前工作目录。
当通过 shell 运行时,该目录就是您当前所在的目录。在 man systemd.exec
中,您可以找到“WorkingDirectory=` 指令,该指令记录了 systemd 的默认当前工作目录:”当 systemd 作为系统实例运行时默认为根目录”。
因此,如果您的 Temperature.py
位于 /var/www/Raspberry-Pi-Status
中,则设置:
workingDirectory=/var/www/Raspberry-Pi-Status in your `[Service]` section.
关于javascript - 当 Node Js 应用程序开始使用 Systemd 时,Nodejs 应用程序不会生成 python 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682724/