1

I'm building a toy system monitor for which I parse multiple files from /proc. Among other values I parse the uid for every process from /proc/$pid/status. Later I map the process' uid to the username which I parsed from /etc/passwd. But in some rare cases my program crashes, because it can't find the username. Do I need to parse other files as well in order to get a complete uid -> username mapping?

Picard
  • 123

1 Answers1

1

Linux supports modular account databases. In addition to the 'files' database (/etc/passwd), user accounts can be stored in SSSD, in BDB, in a network database (LDAP, YP, NIS, Hesiod, Active Directory, SQL), or they can even be dynamically generated by the database module itself (systemd DynamicUsers).

To make this work, you should never parse /etc/passwd and other files directly (well, unless you're specifically making a local-user management tool).

You should use the libc-provided functions such as getpwuid() or getgrgid() to look up user names and UIDs, and from shellscripts you should use the getent or id CLI tools to perform lookups.

In general, you should also never crash if the mapping fails, since it's possible that the account might have been deleted, or that the process belongs to a container which has its own UID range. Just show the UID when that happens.

grawity
  • 501,077