문제

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