Changing process name in Mono

Published on Thursday, February 9, 2006

Banshee 0.10.5 supports changing the process name from "mono" to "banshee" using the prctl call. This makes "killall banshee" work. While this is nothing to marvel over, I have been a little taken aback by the amount of inquiry over this feature. In the past few days, a large number of people have asked me, "how did you do this." Here's a brief description of "how."

This had been discussed over private email a few months ago, but was recently touched on again as a bug filed against Beagle.

The short answer is, if you want your mono app to be "killall-able," then do this:

using System.Runtime.InteropServices;
using System.Text;

...

[DllImport ("libc")] // Linux
private static extern int prctl (int option, byte [] arg2, IntPtr arg3,
IntPtr arg4, IntPtr arg5);

[DllImport ("libc")] // BSD
private static extern void setproctitle (byte [] fmt, byte [] str_arg);

public static void SetProcessName (string name)
{
try {
if (prctl (15 /* PR_SET_NAME */, Encoding.ASCII.GetBytes (name + "\0"),
IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0) {
throw new ApplicationException ("Error setting process name: " +
Mono.Unix.Native.Stdlib.GetLastError ());
}
} catch (EntryPointNotFoundException) {
setproctitle (Encoding.ASCII.GetBytes ("%s\0"),
Encoding.ASCII.GetBytes (name + "\0"));
}
}

...

try {
SetProcessName ("banshee");
} catch (Exception e) {
Console.Error.WriteLine ("Failed to set process name: {0}", e.Message);
}

Now "killall banshee" works. Also consider using "exec -a banshee ..." in your Bash wrapper to make process listings look better. There are more details provided in the bug, as well as some implications you should be aware of if you do this with your Mono app.

Code snippet updated on 2007-11-12 to show how to support BSD systems and reflect a known fix for 64 bit systems. The above code is known to be bug free and tested in many production applications.