iceblaze
iceblaze

Reputation: 21

bash script returns empty ps results, same one-liner on CLI returns correctly

I have a bash init script that runs this command:

sudo -umyuser APPLICATION_ENV=production php script/push-server.php >> /var/log/push-server.log 2>&1 &

I then try to capture both pids and put them into a file:

echo $! > /var/log/push_server.pid
childpid=$(ps --no-heading --ppid $! | tail -1 | awk '{ print $1 }')
echo $childpid >> /var/log/push_server.pid

However, if I use the --no-heading flag it returns blank. If I run that very same ps command on the command line, it returns the proper pid number. The same happens if I modify the command a little bit like so:

childpid=$(ps --no-heading --ppid $! | awk '{NR>1}' | tail -1 | awk '{ print $1 }')

I've tried removing the NR, tail, adding the --no-header, and even going all the way down to just doing:

chidlpid=$(ps --no-heading --ppid $!) 

and it still won't return the child pid.

Any ideas?

Upvotes: 2

Views: 1231

Answers (2)

iceblaze
iceblaze

Reputation: 21

Thanks for everyone who jumped in to help! The answer was indeed to add a sleep n:

    sudo -umyuser APPLICATION_ENV=production php script/push-server.php >> /var/log/push-server.log 2>&1 &
    mainpid=$!
    echo $mainpid > /var/log/push_server.pid
    sleep 3
    childpid=$(ps --no-heading --ppid $mainpid | tail -1 | awk '{ print $1 }')
    echo $childpid >> /var/log/push_server.pid
    echo -n "push_server started on pid $mainpid $childpid"
    return

Upvotes: 0

fejese
fejese

Reputation: 4628

The second time you use $! you actually use the pid of the echo. Save it in a variable for later use.

Above statement is not true, as @mklement0 pointed out $! only updated when a new background process is started.

The most likely problem therefore is the timing: maybe the child process is not forked yet by the time the script checks for the pid.

Upvotes: 1

Related Questions