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?

5
  • At least for Linux, have you looked at your system logs? The system (journald) is probably already tracking this information for you. Also, if you are determined to reinvent the wheel, you could put a script with the same name before the command you want to execute in the path. Then have that script launch and log. – Señor CMasMas Jan 14 at 17:46
  • @SeñorCMasMas this may work, but I'm not using systemd (void linux). is there something similar that's more portable? – Skylar Bleed Jan 14 at 18:19
  • Maybe you mean "I want to run binary file from a shell and wait until it returns a control to me"? In this case please read man time. Just don't call this thing a "process starts", that's really an "application start, some initialization and backgrounding / exit", a much more complex thing. – Nikita Kipriyanov Jan 14 at 19:12
  • @NikitaKipriyanov No, that is not what I mean. I want to track every time an application is run. I do not care about what happens after it starts, only that I know how many times it runs – Skylar Bleed Jan 14 at 19:21
  • Use auditd. See here: serverfault.com/questions/736753/… – Nikita Kipriyanov Jan 14 at 19:27
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.