How can a process appear to have different name in ps output?

Manipulating the name in the process list is a common practice. E.g. I have in my process listing the following:

root      9847  0.0  0.0  42216  1560 ?        Ss   Aug13   8:27 /usr/sbin/dovecot -c /etc/dovecot/d
root     20186  0.0  0.0  78880  2672 ?        S    Aug13   2:44  \_ dovecot-auth
dovecot  13371  0.0  0.0  39440  2208 ?        S    Oct09   0:00  \_ pop3-login
dovecot   9698  0.0  0.0  39452  2640 ?        S    Nov07   0:00  \_ imap-login
ericb     9026  0.0  0.0  48196  7496 ?        S    Nov11   0:00  \_ imap [ericb 192.168.170.186]

Dovecot uses this mechanism to easily show what each process is doing.

It's basically as simple as manipulating the argv[0] parameter in C. argv is an array of pointers to the parameters with which the process has been started. So a command ls -l /some/directory will have:

argv[0] -> "ls"
argv[1] -> "-l"
argv[2] -> "/some/directory"
argv[3] -> null

By allocating some memory, putting some text in that memory, and then putting the address of that memory in argv[0] the process name shown will have been modified to the new text.


Changing argv[] is not portable. On Linux you can't simply change argv[0] to point to a longer string either. You'd have to overwrite the existing arguments and take care not to overwrite the environment variables that follow in the address space.

libbsd provides an implementation of setproctitle(3) for Linux that makes this much easier.


There are two Linux-standard ways to do this, one of which comes from glibc and might be portable to other non-Linux systems:

  • glibc pthread_setname_np() is probably the better method
  • Linux prctl() also works

It's possible that changing argv[0] used to work, but at least on my current Linux system it does nothing to the output in ps.

See this answer for more details and a code example: https://stackoverflow.com/a/55584492/737303

Tags:

Linux

Process