Setting the process name in Ruby

When running a ruby application by default the process is shown like 1234 ruby ruby test.rb when running ps -o pid,comm,args on a linux box. The command, comm, is the process name according to the application, and args are the arguments passed to the process on startup. Since the arguments are passed as a string this means that a programm can theoretically modify them to change what is displayed. In ruby this means that one can change the value of the $0 variable to change what is displayed by programms like top for example, this does however not change the actuall process name but just changes what is stored in the process agruments. A problem with this arises when the process is forked via a tool like upstart, which means that its arguments like any other process memory is copy-on-write, and therefor a modification of the arguments will cause a copy and modification, instead of changing the underlying string, this in turn means that overwriting $0 will not change the output in top or other tools.
With ruby 2.1 a new API appears in ruby setproctitle which is available to change this, unfortunatly this does not work everywhere and is also not available pre 2.1. Luckily linux offers an API to set the process title via prctl which can easily be leveraged via FFI to change the process title to whatever is needed (as long as it is below 15 characters).
https://gist.github.com/sideshowcoder/8057955257e645b7058a.js
Now 1234 mytitle ruby test.rb can be seen when running ps -o pid,comm,args when calling ProcessCtrl.set_process_name "mytitle" from the test.rb script.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.