已验证 可行 已经用上了
代码稍微优化了下 加入了服务进程监控,防止进程数过载
const { exec, spawn } = require(‘child_process’);
const http = require(‘http’);
const commands = [‘cd /usr/home/wuming/sb && ./start.sh’];
const checkInterval = 500;
var pids = [];
function logWithTimestamp(message) {
const timestamp = new Date().toISOString();
console.log([${timestamp}] ${message}
);
}
function checkProcess(processName, callback) {
exec(pgrep ${processName}
, (error, stdout, stderr) => {
if (error || !stdout) {
// 如果找不到进程,回调传递false
callback(false);
} else {
// 如果找到进程,回调传递true
callback(true);
}
});
}
function run(i) {
try {
logWithTimestamp(Checking if 'sb' process exists...
);
// 检查 'sb' 进程是否存在
checkProcess('sb', (exists) => {
if (exists) {
logWithTimestamp(`'sb' process already running, skipping command: ${commands[i]}`);
} else {
logWithTimestamp(`'sb' process not found, starting command: ${commands[i]}`);
const process = spawn('bash', ['-c', commands[i]]);
pids[i] = process.pid;
process.on('error', (err) => {
logWithTimestamp(`Process failed to start: ${err}`);
pids[i] = -1;
});
process.on('exit', (code, signal) => {
logWithTimestamp(`Process exited with code ${code}, signal ${signal}`);
pids[i] = -1; // 设置为-1以便下一次检测时重启
});
}
});
} catch (e) {
logWithTimestamp(Error launching program: ${e}
);
pids = -1;
}
}
// 启动所有命令
for (let i = 0; i < commands.length; i++) {
run(i);
}
// 定期检查进程是否存活
setInterval(function() {
for (let i = 0; i < pids.length; i++) {
if (pids == -1) {
logWithTimestamp(Process not running, checking 'sb' process...
);
run(i);
} else {
let pid = pids;
exec(ps -p ${pid}
, (error, stdout, stderr) => {
if (error) {
logWithTimestamp(Process ${pid} not found, checking 'sb' process...
);
run(i);
}
});
}
}
}, checkInterval);
// 创建 HTTP 服务器
http.createServer(function(req, res) {
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘The server is running.\n’);
}).listen(3000, () => {
logWithTimestamp(‘HTTP server is running on port 3000’);
});