Keeping the average user from opening two copies of my program I know that this is an impossible task against someone determined, but I'd like to keep mid-average users from being able to open more than one copy of my program at a time.

Here's the quick code I've made:

const tmp = require('tmp'),
    fs = require('fs'),
    path = require('path');

// Randomly generated, constant in each copy of the app
const app_code = '19c2cefbfa76b4887a1d4664704a3fe0';

// Write protection here, although it doesn't help much
const lock = tmp.fileSync({ mode: 0444, prefix: app_code});

const filedir = path.dirname(lock.name);
const filename = path.basename(lock.name);

// Search for already running copies
fs.readdirSync(filedir).forEach(f =&gt; {
    // If it's made by the app and it's not mine
    if (f.includes(app_code) &amp;&amp; f !== filename) {
        // Delete my lock and close
        fs.unlink(lock.name);
        process.exit(1);
    }
});

// Watch for my own lock being deleted
fs.watch(filedir, function(event, who) {
    if (event === 'rename') {
        // If my lock doesn't exist or a new lock has been made
        if (!fs.existsSync(lock.name) || who.includes(app_code)) {
            // Delete my lock and close
            fs.unlink(lock.name);
            process.exit(1);
        }
    }
});

// Main program content, use placeholder here:
setInterval(() =&gt; console.log("Running alone"), 1000);


There are a few issues that I see right off the bat:


Different tmp folders being used
Locks being left in place if the program is terminated, meaning no copies could run


Anything obvious I'm missing?
I suggest you to use resource based locking. Consider the following:


your application uses well known TCP/UDP port. Only single process can bind it.
your application uses some configuration/database/whatever files in predefined places. flock them. Same stands for pid files under /var/run.


It is still possible to separate resources with chroot or containers. But if nothing is shared are there any benefits in forced locking?


  I'd like to keep mid-average users from being able to open more than one copy of my program at a time.


I guess mid-average users won't use network namespaces, chroots or containers. If they will - I bet they have the reasones so let them do the thing.