Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing the output of a process to a file which has the process id in its file name

This is what I'm trying to achieve:

  • Run a command/process in background and have it's output redirected to a temporary file which is named after the process id of the background process.
  • Example:
    • top & // process Id of this background process is 1123
    • The output of top should be stored in a file 1123.temp

Is this possible? Because to truly run it in the background wouldn't we have to do the redirection before marking it as a background process? Or is there some technique to work around this?

like image 413
egorulz Avatar asked Nov 21 '12 11:11

egorulz


1 Answers

You can redirect to a temporary file and then mv that file to the required name e.g.

process > /tmp/process.log &
mv /tmp/process.log /tmp/$!.log

$! is the pid of the previously backgrounded process. Note that the mv simply renames that file. It won't interrupt writing to it.

like image 75
Brian Agnew Avatar answered Sep 20 '22 02:09

Brian Agnew