I've read about the concepts of process accounting in Advanced Unix.
I understand that these accounting records are typically a small amount of binary data with the name of the command, the amount of CPU time used, the user ID and group ID, the starting time, and so on for a process.
But I don't understand how the acct
structure can be accessed.
struct acct ac_data;
How can I access an acct
structure and how can I enable and disable process accounting?
Firstly, it's worth noting that on some systems the process accounting is disabled by default (I know it's disabled on my particular Linux system and on the latest macOS 10.12 by default). This is because logging with binary files is considered by many to violate the Unix philosophy, specifically this part:
With all of that said, there are a few main things you need to do:
Turn on process accounting. You can do this with the
acct(2)
command, I recommend you check out the manpages for your system but here are some for Linux online. You specify where you want to log to with this command, or useNULL
to turn process accounting off.Read in the accounting records. For this you need the
fread(3)
function, which reads in binary data from a file. Note that this isn't cross-platform because each system will likely have different fields for theacct
struct (here you can see the problems with binary interfaces). Again, I highly recommend you read the manpages forfread
, they're very clear about how to use it.Read the fields of the struct. Once you've got the
acct
struct in your program, you can just access the fields like you would any other struct. To know which fields you can use, again, read the manpages. This page shows the fields on one particular system.As you've probably noticed, a common theme here is to read the manpages. They're quite concise and I think it's a great way to piece together how a particular system works. Type in
man 5 acct
on your system and you'll have everything you need to know!