Today on the IRC somebody asked what would be the best way to know if a process already exists in the system. The choice was between using test -d /proc/PID or kill -0 PID.
Both of them do the job, the question here, we want to use the best one. Suddenly I remembered an option that comes with strace and lets you query the number of syscalls for a given trace. Furthermore, we can order based on the number of syscalls.
adm@testing:${~} strace -c -S calls kill -0 1234
kill: No such process
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
-nan 0.000000 0 12 mmap2
-nan 0.000000 0 6 close
-nan 0.000000 0 5 open
-nan 0.000000 0 5 fstat64
-nan 0.000000 0 4 read
-nan 0.000000 0 4 4 access
-nan 0.000000 0 3 brk
-nan 0.000000 0 3 munmap
-nan 0.000000 0 2 mprotect
-nan 0.000000 0 1 write
-nan 0.000000 0 1 execve
-nan 0.000000 0 1 getpid
-nan 0.000000 0 1 1 kill
-nan 0.000000 0 1 dup
-nan 0.000000 0 1 1 _llseek
-nan 0.000000 0 1 fcntl64
-nan 0.000000 0 1 set_thread_area
------ ----------- ----------- --------- --------- ----------------
100.00 0.000000 {52} 6 total
Let’s compute the number of syscalls when using test
.
adm@testing:${~}strace -c -S calls test -d /proc/1234
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
-nan 0.000000 0 7 mmap2
-nan 0.000000 0 5 close
-nan 0.000000 0 3 open
-nan 0.000000 0 3 3 access
-nan 0.000000 0 3 brk
-nan 0.000000 0 3 fstat64
-nan 0.000000 0 2 mprotect
-nan 0.000000 0 1 read
-nan 0.000000 0 1 execve
-nan 0.000000 0 1 munmap
-nan 0.000000 0 1 1 stat64
-nan 0.000000 0 1 set_thread_area
------ ----------- ----------- --------- --------- ----------------
100.00 0.000000 {31} 4 total
The column calls provides the number of performed syscalls. Using test -d /proc/PID gives a better performance due to a minor number of syscalls.