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 😛 I have tinkered around with exec and $PPID but to no avail. My bash-fu is weak 😐 please help me, point me somewhere! Thanks!
The problem here is that each new process started by bash gets new PID and you have to redirect the output of that process before starting it. But you cannot tell what PID will be assigned to that process by OS.
The solution to this problem is not to start a new process, but replace the existing bash process with a new one using
exec.Here is an example. First, we write a basic C program that prints its PID:
Then we write a simple bash script that will print its PID and replace itself with this program using exec:
Now, let’s write a script that will call this
printpid.shscript multiple times:Now, let’s make sure it works:
Be aware that when you are using
execyou cannot put anything else after that in the script as bash shell replaces itself with a new process specified as command line arguments forexec.Good luck hacking!