Last pid process linux

616 views Asked by At

I'm trying to get the last pid of a process (for example sleep). I do this:

# sleep 10 &
[1] 14115

But when I use this command to get the last pid:

# ps aux --sort +start_time | tail -n 4 | awk 'NR==1{print $2 " " $11}'
14125 sleep

The pid is not the same, i don't understand what I'm doing wrong, because if I do the same but without the last part of the command, I get the same pid:

# sleep 10 &
[1] 15853

# ps aux --sort +start_time | tail -n 4
root     15853  0.0  0.1   3364   520 pts/2    S    16:45   0:00 sleep 10
www-data 15871  0.0  0.0   1864   452 ?        S    16:45   0:00 sleep 1
root     15872  0.0  0.2   4344  1168 pts/2    R+   16:45   0:00 ps aux --sort +start_time
root     15873  0.0  0.1   3756   676 pts/2    S+   16:45   0:00 tail -n 4

Thanks in advance

[Solved]

# ps aux --sort +start_time | tail -n 5 | awk 'NR==1{print $2 " " $11}'

another solution for a concrete process

# pgrep -n 'name_of_the_process'
2

There are 2 answers

1
choroba On BEST ANSWER

The awk process is started, and occupies another line in the output. Try tail -n 5, but it's not reliable, as another process could be started in between, anyway. See psgrep.

0
stathisv On

You could get the pid of the last process with: echo $!