1

I'm attempting to make a script which tracks how many times you execute a specific process. I want to detect when the process starts and then log it.

The psuedo-code would be something like this:

while (true) if (process started) then log(process)

Is there an easy way to do this (preferably in shell but C is also fine) on either Linux or NetBSD?

Ahmed Ashour
  • 2,490

2 Answers2

0

On Linux, if you know the name of the process (the executable path), then you can loop through /proc/ dir for each PID and check the exe file in each of those PID directories. This file will be the same as the executable path of the process you're looking for.

See pseudo code:

proc_exe="" # The full path of the executable you're interested in checking.

for d in /proc/<pid> do; if [ ${d}/exe -eq ${proc_exe} ]; then # Found the PID of the process you're interested in. fi done

This technique is better than systemd and friends and works on other Linux distros too.

On NetBSD, there's a file cmdline which gives you the whole argv as it went to the process. Slightly different semantics but almost same outcome.

For Linux, see proc and for NetBSD, see mount_procfs.

0

Traditionally in Unix and its derivatives (including NetBSD) one way to do this is to enable process accounting.

On NetBSD process accounting can be enabled and started as follows:

echo accounting=YES >> /etc/rc.conf
/etc/rc.d/accounting start

Something similar should be possible on other BSDs and Unix derivatives.

The sa(8) command can be used to analyze and summarize the accounting data generated by the kernel, and by default it will print of information about each command that has been run since the current accounting file was first started, including how often each command has been run.