'How to set the process title without 3rd library in Python?
A lot of implementations employ 3rd library, such as setproctitle. So can we implement the functionality manually?
Solution 1:[1]
Of course, this functionality can be implemented by the Python raw approach. As we all know, Python has the standard library ctypes. By using this library, we can do the syscall. Meanwhile, other implementations are the same as to call system function to achieve the objective.
As the code below shows:
import ctypes
libc = ctypes.CDLL('libc.so.6')
progname = ctypes.c_char_p.in_dll(libc, '__progname_full') # refer to the source code of glibc
with open('/proc/self/cmdline') as fp:
old_progname_len = len(fp.readline())
if old_progname_len > len(new_name):
# padding blank chars
new_name += b' ' * (old_progname_len - len(new_name))
# for `ps` command:
# Environment variables are already copied to the Python program zone.
# We can get environment variables by using `os.environ`,
# hence we can ignore both reallocation and movement.
libc.strcpy(progname, ctypes.c_char_p(new_name))
# for `top` command and `/proc/self/comm`:
buff = ctypes.create_string_buffer(len(new_name) + 1)
buff.value = new_name
libc.prctl(15, ctypes.byref(buff), 0, 0, 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wotchin |
