tags:

views:

30

answers:

2

I've searched for a while but i can't either find an answer or come up with a solution of my own, so I turn to you guys. First question I actually ask here :)

I would like to run several instances of the same program, and redirect each of these programs' standard output to a file that contains that same process' pid, something like:

my_program > <pid of the instance of my_program that is called in this command>.log

I'm aware that this is not even close of the way to go :P I have tinkered around with exec and $PPID but to no avail. My bash-fu is weak :| please help me, point me somewhere! Thanks!

A: 

You cannot know the PID of a process before you created it.

Therefore this is not possible, you should rewrite the program that is called, to use getpid() to forge a log name from its own PID.

Benoit
+2  A: 

You can wrap your program execution into bash script. The bash process will be replaced with your program on exec call. So:

#!/bin/bash
exec my_program > $$.log
dma_k
This solved my problem! Thanks! Actually, I tried something similar, only instead of running a script as a separate bash job so that exec could replace that instance of bash with my_program, I tried the same concept but using the -c command line option for bash, but it didn't work.
ticklemynausea
bash -c "exec echo $$" outputs 3357. // on the same shell, echo $$ outputs 3357
ticklemynausea
@ticklemynausea: You need think about when `$$` is actually substituted by bash with the value. If you write (and most of us do it this way) `bash -c "exec sleep 300 > $$.log"`, the `$$` is not replaced by the bash we are about to run, but with parent (e.g. current) bash! Now feel the difference: `bash -c 'exec sleep 300 > $$.log'`
dma_k