Shell script to check if process is running

2019-03-05 01:42发布

There is some weird behavior going on that leads me to think there may be something going on...

So I have a shell script executed by cron. Basically it is meant to check if Node.js is running. If so, log the date... if not then log nothing! At the time I built it I tested it and saw it logged when a node script was running and did not log when it stopped running...

Recently I knew Node went down and thought it was the perfect opportunity to check if the script did what its supposed to do. It didnt! And it does not... :(

Here is the script:

#!/bin/bash

if ps -Al | grep -v grep | grep -q node 
then
        date > /etc/nodeCheck.log 
else
        date > /dev/null 
fi

Permissions on this .sh are correct, paths used exist, running

$ps -A | grep -v grep | grep -q node

returns nothing and

$echo $?
1

So shouldn't it be going to the else block? node is a process started after bootup. The shell script does not work correctly both when run by cron or by me when I am SSH'd in.

Am I missing something fundamental here?

TIA

Niko

3条回答
干净又极端
2楼-- · 2019-03-05 02:11

Another way to check process by name:

if killall -s 0 node &>/dev/null; then
    ...

Or if shell doesn't support &>:

if killall -s 0 node >/dev/null 2>&1; then
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-05 02:13

This isn't exactly an answer to your question, but perhaps it's a solution to your problem.

One of the issues I've had with Node is that the server process doesn't store its pid anywhere. So rather than having a thing that cron runs to "check" whether it's running, I wrapped the node executable in a script that simply relaunches it if it crashes.

#!/bin/sh

cd /path/to/my/software

while sleep 1; do
  date '+%Y-%m-%d %T - nodejs restarted' 
  logger "nodejs restarted"; date '+%Y-%m-%d %T - nodejs restarted' | Mail -v -s "nodejs restarted on `hostname -s`" admin@example.com
  node main.js
done

This script gets run once, when the system starts up. It launches Node, and if Node never crashes, all is well and good, but if it does, I get a notification, a log entry, and a restart.

I run this in FreeBSD, but it should run equally well in Linux or other operating systems.

查看更多
Rolldiameter
4楼-- · 2019-03-05 02:21

Unless you're running BSD ps, you should be able to use a -C flag or pgrep

-C cmdlist      Select by command name. This selects the processes whose executable 
                name is given in cmdlist.

For example,

if ps -C node > /dev/null
then
        date > /etc/nodeCheck.log 
else
        date > /dev/null 
fi

or

if pgrep node > /dev/null
then
        date > /etc/nodeCheck.log 
else
        date > /dev/null 
fi
查看更多
登录 后发表回答