0

I need a linux / unix command that will execute another command and write the PID of the command it executes to a file... is there such a command?

I am not looking for any scheme that puts processes in the background and leverages the shell var $!

Example:

Assume the command I am looking for is execwritepid. I need to be able to call:

execwritepid -e "/usr/bin/script -f sometext.log" -f /var/log/script.pid

Such that the PID of script -f sometext.log is written to /var/log/script.pid

script is the the command I'm executing.

The explicit suggestion, based on Daniel Pittman's answer is:

bash -c 'echo $$ > /var/log/script.pid && exec /usr/bin/script -f sometext.log'
Mike Pennington
  • 8,305
  • 9
  • 44
  • 87
  • Be careful: there is an actual UNIX/Linux command `script`; if that is the actual name, you should choose another. – Mei Feb 21 '12 at 22:41
  • @David, note what I said at the bottom of the question, I'm getting the pid for the UNIX script command you just mentioned – Mike Pennington Feb 21 '12 at 22:43

1 Answers1

3

You can do what you want with this code:

echo $$ > /var/log/script.pid && exec /usr/bin/script

exec replaces the current process with another - which means that it retains the current pid.

If you want your parent script to carry on you can wrap that:

bash -c 'echo $$ && exec /usr/bin/script'

That will run the subcommand in a new shell, record the PID, then replace itself with the other process.

Daniel Pittman
  • 5,842
  • 1
  • 23
  • 20
  • Thank you, but I'm still having a problem... I can't figure out how to make the `exec` option send the `-f sometext.log` option to `script` – Mike Pennington Feb 21 '12 at 22:46
  • If you put `exec` in front of a regular bash command line it will replace itself with that command, rather than run the command and wait for it to exit. So, `echo $$ > /var/lib/script.pid && exec /usr/bin/script -f sometext.log` should do exactly what you want. – Daniel Pittman Feb 21 '12 at 22:49