Process ID of Command

I need a way to get the Process ID of the last command I executed in a script. Not the last background process but the last command.

For example, suppose I am executing a binary inside a script like so.

binary.program argument1 argument2

If this binary program runs fast, is there a command that will tell me the last PID of that command. In other words, can I get the PID of a command I execute within a shellscript? Is my only alternative to get information like this by running the process in the background and using "$!"?

Any thoughts are appreciated. Thanks in advance.

You could do that with system call tracer,

in Linux available as strace

on Solaris as truss commands

take this sample,

>cat script.zsh
#! /bin/zsh
  ./while
exit 0

while binary is nothing but, endless loop

#include <stdio.h>
int main()
{
  while(1) {
  }
  return 0;
}

Run it as,

strace zsh script.zsh > out.log 2>&1

And now in the out.log strace would have traced system call of the script which spawned the binary within it, it would be available as the return value of clone system call.

In the out.log it should be something like,

clone(parameters) = return value;

Return value above is the pid of the binary ( child ) spawned by the script ( parent )

Try it out! :slight_smile:

I like your alternative, however I unfortunately need to make this work on HP-UX out of the box. So I do not have trace or tusc available on this server so I cannot use this method. Thanks for the reply, I will keep digging and see if I can find another solution. Thanks again. :slight_smile:

Am surprised, :confused:

why is that there isnt tusc (system call tracer for HP-UX) available ? :rolleyes:

Well, tusc is not default, it is something that has to be installed extra. I am not a sysadmin on this box so I cannot make the call of adding it. Since what I was trying to do would go elsewhere, I have to also assume the HP-UX box sitting elsewhere would also not have tusc installed.