How to get process id of called process

Hi,
inside my script s1.sh i am calling another script s2.sh
After s2.sh finishes, i want to print the process id of the s2.sh (that was used)
I can't use ps -ef command, since by this time s2.sh has already finished.
Is there a way to capture pid of s2.sh right when it's called?

I don't want to call s2.sh in the background, even if i did, by the time i use ps command to find the pid value, the s2.sh might have already finished in no time.

In windows script, the call to a process returns the associated pid immediately

Another question, how do i get the current pid without using the current process name?

Thanks,
-srinivas yelamanchili

No need to use ps,

use echo $!

this would give the pid of the last background process and there is no constraint that the background process should be executing while echo $! value is retrieved

thanks Madhan.

Now, i really don't want to run in background.
Also i want to get the pid and return code of the called process, once it's finished.

Thanks

use echo $? - for the return value -as returned by the process

Not very elegant, but should work.

In your s2.sh, save the return code of the process and append the process id to it as well or vice versa. Use then accordingly in the parent script.

ret_pid=$?"#"$$
exit ${ret_pid}

What are you going to do with the pid of a process *after* that process has finished?

As that pid is a candidate to get reused any time after the process was reaped.

I think it should be for some logging reasons.

something like
dumper process with pid:<> completed with status: <>

for these kind of information pid info becomes mandatory to fill in the logs

I got the solution,

In s1.sh script:
---------
capture pid of current script
S1PID=??

#call s2.sh in the background
s2.sh &

#capture the pid of the most recent background process
S2PID=$!

#wait for s2.sh to finish
#and capture the return code of s2.sh
wait $S2PID
RC=$?

Here, even if the s2.sh finishes in no time, S2PID=$! will still return it's pid and 'wait $S2PID' will finish with return code of s2.sh, even if s2.sh has finished long before the wait command was issued.

The reason why i want to get the pid, is to keep a list of kicked off process and cleanup any 'hung up' process in future. Even though the pid's are reused, the pid+time combination will be unique.

Earlier i said i don't want to run s2 in background, that's because i didn't want to continue s1 without s2 finishing first. However, if i can capture the pid of s2 only by running it in background, then i better run it that way and then wait for it to finish, before continuing with s1.

Thanks to all for your input.
-srinivas yelamanchili

Underneath *all* processes are really executed in the background, it's what the parent chooses to do between the fork and the wait that makes the difference.