Python: Changing process name with setproctitle
I have a python script which launches a number of C++ programs, each program is passed a command line parameter as shown below
process_path "~/test/"
process_name "test"
num_process = 10
for p in range(1, num_processes, 1):
subprocess.Popen([process_path + process_name, str(p)], shell = False)
Is it possible to us setproctitle to rename each of these process so that I cou开发者_JAVA技巧ld include the command line parameter as part of the process name, if so , how would you do it?
setproctitle can only change it's "own" process title as I would presume a safety element, but the technique of rewriting the process table is an ancient rootkit technique -- so clearly it is possible.
Furthermore, setproctitle has support for multiple operating systems, so the method in which you change the process information may vary, but for the sake of explanation I'll presume you're using this under Linux and lets see what we have.
Linux uses prctl(), which looks like you use prctl(PR_SET_NAME, "my_new_name");, and this only works on the calling process. So it doesn't look like there's an 'easy' way to do this using the setproctitle module -- you can only modify yourself.
Your best bet is to modify your C++ code so that it uses prctl.
If you're not using Linux, post what you are using as other operating systems provide other opportunities and methods that differ greatly from the limitations of prctl.
If you pass an kwarg executable
to subprocess.Popen
, you can use the first argument in the argument list:
subprocess.Popen(['some string you choose', str(p)],
executable=process_path+process_name, shell=False)
The docs say: "On Unix, it becomes the display name for the executing program in utilities such as ps."
Windows-only: the process name usually means the actual executable image which is running (e.g. calc.exe). The process title on the other hand (it's the text that shows up on your taskbar) can easily be changed for console (CUI) apps using the start command instead of running the app directly (give the title as the first argument; use start /? for details):
for p in range(1, num_processes, 1):
subprocess.Popen(['start', str(p), process_path + process_name, str(p)], shell = False)
# ^ this is the title
For GUI apps it's slightly more difficult, and much less likely to be necessary.
精彩评论