Measure process changes by identity
Distinguish a process counter delta from PID reuse or a counter reset.
A PID can be reused
A process ID identifies a running process within a host at a particular time. After that process exits, the operating system can assign the same number to another process. Subtracting counters by PID alone can therefore compare two unrelated programs.
The recorded start token acts as an additional identity field. First match host and PID, then require the token to remain equal before subtracting CPU milliseconds. A host name matters too: process 42 on one server is not process 42 on another. Treat these fields as opaque validated values rather than trying to interpret a start token as shell syntax.
A smaller counter is not negative work
When the identity matches but the counter decreases, classify a counter_reset. Do not report a negative CPU delta. When no earlier host/PID exists, the process is new and has no measurable interval in this dataset. This report follows the after snapshot; processes absent from it do not produce synthetic zero rows.
The inputs are fictional process exports. The exercise does not inspect or control browser-host processes. In a live collector, elapsed sample time and CPU accounting units also need validation before deriving a utilisation percentage. Here the simpler millisecond delta keeps the identity problem visible before the next lesson uses those same identities to guard a simulated stop request.
awk -F '\t' 'NR>1 {print $1 ":" $2 " started " $3}' after.tsv
Put it into practice.
before.tsv and after.tsv have host<TAB>pid<TAB>start_token<TAB>cpu_ms, unique host/PID pairs and validated nonnegative counters. For every after row, print host<TAB>pid<TAB>delta_ms<TAB>state sorted by host then numeric PID. No before pair: new; changed start token: reused_pid; same token but lower counter: counter_reset; otherwise measured with after-minus-before (including zero). All non-measured rows use - for delta. Never combine different hosts or tokens.
See an explained solution
export LC_ALL=C
printf 'host\tpid\tdelta_ms\tstate\n'
awk -F '\t' 'FILENAME==ARGV[1]{if(FNR>1){key=$1 SUBSEP $2;start[key]=$3;cpu[key]=$4}next}
FNR>1{
key=$1 SUBSEP $2;delta="-";state="new"
if(key in start){
if(start[key]!=$3)state="reused_pid"
else if($4<cpu[key])state="counter_reset"
else {state="measured";delta=sprintf("%.0f",$4-cpu[key])}
}
printf "%s\t%s\t%s\t%s\n",$1,$2,delta,state
}' before.tsv after.tsv | sort -t $'\t' -k1,1 -k2,2n
The report requires both stable identity and a monotonic counter before measuring a delta. This prevents reused PIDs, host collisions and counter resets from producing misleading utilisation evidence.