Reputation: 11356
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?
Simply running (if) pidof node
won't work, because there might be other unrelated node scripts running.
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.
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?
Upvotes: 3
Views: 5600
Reputation: 829
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!');
}
});
Upvotes: 3
Reputation: 241
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.
Upvotes: 7
Reputation: 185179
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
Upvotes: 4