Give actual pid as argument

Hi,

I run a command in the shell that run another process. I need a way to provide the command's pid to the subprocess. For instance, if I run the command foo:

foo process_to_run -p foo's_pid

I would like to pass to process_to_run the pid of the foo command, or something that link process_to_run to foo.
I would like to access to foo from process_to_run

Is there any way to do that?
Thanks
D

That's an interesting request. It's hard to know your PID in advance!

But not impossible: The exec command can be used to replace your shell's PID with a command. The process being executed will change but the PID won't.

So if you do this inside its own independent little shell script, it should be doable like this:

#!/bin/sh

exec foo process_to_run -p $$
# Unless exec fails somehow, no commands below here will be run.
# The shell will no longer exist, having been replaced by foo!
echo "exec failed code $?" >&2
exit 1

Where $$ is the shell's PID. Since we're running foo with exec, the shell will be replaced with foo, and have the precise same PID as it when all is said and done.

1 Like

That's great!

Thanks a lot

1 Like