Finding the command for a specific PID in Linux from Python

后端 未结 7 853
半阙折子戏
半阙折子戏 2020-12-19 05:33

I\'d like to know if it\'s possible to find out the \"command\" that a PID is set to. When I say command, I mean what you see in the last column when you run the command \"t

7条回答
  •  囚心锁ツ
    2020-12-19 06:32

    Look in /proc/$PID/cmdline, and then os.readlink() on /proc/$PID/exe.

    /proc/$PID/cmdline is not necessarily going to be correct, as a program can change its argument vector or it may not contain a full path. Three examples of this from my current process list are:

    • avahi-daemon: chroot helper
    • qmgr -l -t fifo -u
    • /usr/sbin/postgrey --pidfile=/var/run/postgrey.pid --daemonize --inet=127.0.0.1:60000 --delay=55

    That first one is obvious - it's not a valid path or program name. The second is just an executable with no path name. The third looks ok, but that whole command line is actually in argv[0], with spaces separating the arguments. Normally you should have NUL separated arguments.

    All this goes to show that /proc/$PID/cmdline (or the ps(1) output) is not reliable.

    However, nor is /proc/$PID/exe. Usually it is a symlink to the executable that is the main text segment of the process. But sometimes it has " (deleted)" after it if the executable is no longer in the filesystem.

    Also, the program that is the text segment is not always what you want. For instance, /proc/$PID/exe from that /usr/sbin/postgrey example above is /usr/bin/perl. This will be the case for all interpretted scripts (#!).

    I settled on parsing /proc/$PID/cmdline - taking the first element of the vector, and then looking for spaces in that, and taking all before the first space. If that was an executable file - I stopped there. Otherwise I did a readlink(2) on /proc/$PID/exe and removed any " (deleted)" strings on the end. That first part will fail if the executable filename actually has spaces in it. There's not much you can do about that.

    BTW. The argument to use ps(1) instead of /proc/$PID/cmdline does not apply in this case, since you are going to fall back to /proc/$PID/exe. You will be dependent on the /proc filesystem, so you may as well read it with read(2) instead of pipe(2), fork(2), execve(2), readdir(3)..., write(2), read(2). While ps and /proc/$PID/cmdline may be the same from the point of view of lines of python code, there's a whole lot more going on behind the scenes with ps.

提交回复
热议问题