Here's one simple cross platform scheme that just creates a local server on a known port and then any future instances will try to create the same server and fail because another instance is already running.
One advantage to using a server like this is that the OS will automatically close and cleanup the server if the process dies for any reason so you don't ever get a "stuck" resource like can happen when using some other techniques (like lock files).
const http = require('http');
// create Sentinel server
let server = http.createServer(function(req, res) {
res.send("ok");
});
// make sure this server doesn't keep the process running
server.unref();
server.on('error', function(e) {
if (e.code === "EADDRINUSE") {
console.log("Sentinel server already running - can't run more than one instance");
process.exit(1);
} else {
console.log(e);
}
});
server.listen(8399, function() {
console.log("Sentinel server running")
});
Other schemes that can be used:
- Search list of running processes
- Use a lock file
- Use add-ons like find-process
You can also use a named pipe instead of a port like this (code below works on Windows) or a domain socket on *nix:
const http = require('http');
const path = require('path');
// create Sentinel server
let server = http.createServer(function(req, res) {
res.send("ok");
});
// make sure this server doesn't keep the process running
server.unref();
server.on('error', function(e) {
if (e.code === "EADDRINUSE") {
console.log("Sentinel server already running - can't run more than one instance");
process.exit(1);
} else {
console.log(e);
}
});
server.listen(path.join('\\\\?\\pipe', 'myUniqueServerPipeName'), function() {
console.log("Sentinel server running")
});