简体   繁体   中英

Detect if specific node.js script is running from bash

Read as: Detect (if specific node.js script is running) from bash .


I have a server that runs a specific node.js script on certain actions and certain cron intervals.

The script might take a few hours to finish, but is not supposed to run more than once at the same time.

Is there a way in sh or bash to detect if the specific script is already running?


process

Simply running (if) pidof node won't work, because there might be other unrelated node scripts running.

pidfile

The closest half solution I can think of is touch /tmp/nodescript.lock and only run the script if it does not exist. But apparently /tmp doesn't (always) get cleaned on a server crash/reboot.

secret option number 3

Perhaps there's some other simple way I'm not aware of. Maybe I can give a process some kind of static identifier, which is gone when the process is. Any ideas?

When you invoke a script with nodejs, it appears in the process list such as:

user       773 68.5  7.5 701904 77448 pts/0    Rl+  09:49   0:01 nodejs scriptname.js

So you could simply check ps for its existence with a simple bash script:

#!/bin/bash

NAME="scriptname.js" # nodejs script's name here
RUN=`pgrep -f $NAME`

if [ "$RUN" == "" ]; then
 echo "Script is not running"
else
 echo "Script is running"
fi

Adjust it up to your needs and put into cron.

I recommend you to use a robust lock mechanism like this :

#!/bin/bash

exec 9>/path/to/lock/file
if ! flock -n 9  ; then
   echo "another instance of $0 is running";
   exit 1
fi

node arg1 arg2 arg3...

Now, only one instance of a node script can be run at once

I came across the same problem and I ended up with a completely NodeJS based solution.

I used this awesome module named ps-node .

You can look up if a specific process is already running before you fire up your code.

ps.lookup({
    command: 'node',
    arguments: 'your-script.js',
},
function(err, resultList){
    if (err) {
        throw new Error(err);
    }
    // check if the same process already running:
    if (resultList.length > 1){
        console.log('This script is already running.');
    }
    else{
        console.log('Do something!');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM