raffian
raffian

Reputation: 32056

Output PID to file from process executed in bash script?

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

Upvotes: 2

Views: 1641

Answers (2)

mattbornski
mattbornski

Reputation: 12543

Might I suggest:

#! /bin/bash

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

derived from Mongo help:

mongod --help

Upvotes: 8

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

./mongo-linux64-202/mongod --fork &
pid=$(jobs -p | tail -n 1)

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

Upvotes: -1

Related Questions