2

I've got this simple bash script that starts a server process. I want to output the pid of the server process to a file, pid.txt. After some quick searching on SO, I came up with this approach, but it seems to give me the pid of the bash script, not the server process executed from the script. Note: the --fork is required for my server process to run as a daemon to output data to a separate log file, and I suspect that's causing the issue here based on this previous SO question, hoping there's a way around this.

#! /bin/bash

./mongo-linux64-202/mongod --fork &
pid=$!

printf "%s\n" "$pid" > pid.txt
Community
  • 1
  • 1
raffian
  • 31,267
  • 26
  • 103
  • 174

2 Answers2

8

Might I suggest:

#! /bin/bash

./mongo-linux64-202/mongod --pidfilepath ./pid.txt --fork &

derived from Mongo help:

mongod --help
mattbornski
  • 11,895
  • 4
  • 31
  • 25
  • Tried that, but it does not create the file... `#! /bin/bash ./mongodb-linux-x86_64-2.0.2/bin/mongod --pidfilepath pid.txt --fork --dbpath /opt/mongo/data/db1/dbs --port 33479 --logpath /opt/mongo/data/db1/log/db1.log -logappend &` – raffian Feb 23 '12 at 22:11
  • Try making the pidfilepath more explicit: ./pid.txt (or even better /home/raffi/pid.txt or some other appropriate absolute path). It's possible that mongod is interpreting the relative path as relative to some other directory than your PWD. – mattbornski Feb 23 '12 at 22:20
  • Yup, that was the problem, had to be more explicit, changed to `--pidfilepath /opt/mongo/pid.txt`, thanks for the help! – raffian Feb 23 '12 at 22:29
  • using --fork puts the process in the background so you never should need & (but you do need to give it path to the log file as --logpath argument – Asya Kamsky Dec 28 '15 at 18:26
-1
./mongo-linux64-202/mongod --fork &
pid=$(jobs -p | tail -n 1)

Though look first whether mongod is willing to report its pid somehow.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • 1
    What exactly does `pid=$(jobs -p | tail -n 1)` do? Does this work if multiple mongo processes are running on the same machine? – raffian Feb 23 '12 at 22:06