I have a shell snippet:

nohup sudo node server.js >> node.log 2>&1 &

if [ $? -eq 0 ]; then
  echo $! $?
  echo $! > pids
fi

What I expect is if the node server.js run normaly, then record the pid of this process to the file: pids.

But it does'nt work, the $? is always 0 because it is the status of sudo process? And the $! is also not the pid of the process of node command.

So how can I get the correct return code and pid of the node server.js in the above shell script?

有帮助吗?

解决方案

My final solutions:

#!/usr/bin/env bash

ROOT=$(cd `dirname $0`; pwd)

sudo kill -9 `cat ${ROOT}/pids` || true

nohup sudo node server.js >> node.log 2>&1 &

sleep 1

pid=$(ps --ppid $! | tail -1 | awk '{ print $1 }')

if echo $pid | egrep -q '^[0-9]+$'; then
    echo $pid > ${ROOT}/pids
else
    echo 'server not started!'
fi

其他提示

When you run a command in the background, there's no sensible way for the shell to get the return code without waiting for the process to finish (i.e., node is no longer running). Therefore even these have return code 0:

$ false &
$ does_not_exist &

It seems what you want to do is to check whether a daemon started properly, which completely depends on the daemon. In your case you've started a Node.js server, so you could simply run something like this (untested):

test_if_server_is_running() {
    tries=10
    while [ "$tries" -gt 0 ]
    do
        let tries--
        wget http://127.0.0.1/some_server_path && return
        sleep 1
    done
    return 1 # Did not start up in at least 10 seconds
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top