Monday, October 18, 2010

Changing process name of python script in linux

Whenever you run a python script, it comes with the name "python" in system monitor, which is not very desirable.
The well know way of changing name of process in C is changing the argv[0] value. But, that wont work in python.

To change the process name is python, you have no other way but to load the shared C library and call its function. Well, to do so, we are provided with ctypes in python.

Here is the function which will takes its argument as the new name. I used "man prctl" & content of this "/usr/include/linux/prctl.h"


def set_procname(newname):
    from ctypes import cdll, byref, create_string_buffer
    libc = cdll.LoadLibrary('libc.so.6')    #Loading a 3rd party library C
    buff = create_string_buffer(len(newname)+1) #Note: One larger than the name (man prctl says that)
    buff.value = newname                 #Null terminated string as it should be
    libc.prctl(15, byref(buff), 0, 0, 0) #Refer to "#define" of "/usr/include/linux/prctl.h" for the misterious value 16 & arg[3..5] are zero as the man page says.

All the relevant documentation is available here http://docs.python.org/library/ctypes.html & rest is written as comments..

No comments:

Post a Comment