1

Suppose myprogram is spawned through the terminal (bash) and gets pid of 1234 (different everytime).

I want to redirect, both stdout and stderr, to a tempfile named abc-$PID (if the PID is 1234, use tempfile abc-1234.

The code looks like this now:

myprogram > /tmp/abc-$! 2>&1

it doesn't work

Please help.

sudoer
  • 45
  • 4

1 Answers1

1

Typically, in the shell, the redirection is parsed and handled before the command is run. So the shell has no way of knowing what the child PID is at the time the > is parsed.

But we can cheat... we know our own PID and we can exec the real program. The exec avoids creating a new process ID, so the program executes with the same PID as we started with.

So for example:

$ cat  myprogram 
#!/bin/sh
echo hello.  I am $$
echo err >&2

$ cat wrapper 
#!/bin/sh

exec myprogram > foo-$$ 2>&1

$ ./wrapper 

$ ls
foo-10285  myprogram*  wrapper*

$ cat foo-10285 
hello. I am 10285
err
Stephen Harris
  • 42,369
  • 5
  • 94
  • 123