Bash – Get PID of process started by time

bashlinuxprocesstime

Say I run time ./a.out, then I can get the PID of time by the variable $!. But how do I get the PID of a.out?

Of course, I could parse the output of ps, but I want a more elegant solution.

I've checked man time and couldn't find anything.

The closest I've gotten is time (sleep 10 & echo $!), but because of the fork, the time taken is basically 0 and not 10s as it should be.

Best Answer

By definition, a.out is a child process of time. So time is the parent pid of a.out! here's a test where I replace a.out with sleep 60:

$ time sleep 50 & timepid=$!
$ aoutpid=$(pgrep -P $timepid)
$ ps -o ppid,pid,start,cmd w -p $$,$timepid,$aoutpid

PPID   PID  STARTED CMD
2065  2068 21:34:57 -bash
2068  3297 22:16:05 -bash
3297  3298 22:16:05 sleep 50

(note: where time is actually a shell build-in, so the command above is bash!)

Related Question