命令行命令/命令运行时的pid及获取
命令行输入的命令,和命令运行时的PID并不是同一个。
例如有如下一段代码perf_test.py:
1 import subprocess 2 import time 3 import os 4 import signal 5 6 cmd = "sudo perf record -e cpu-clock -g -p {} -o perf_{}.data".format(os.getpid(), os.getpid()) 7 print(cmd) 8 p = subprocess.Popen(cmd, shell=True) 9 print("cur process pid: {}".format(os.getpid())) 10 print("cur process's parent process pid: {}".format(os.getppid())) 11 12 print("subprocess pid: {}".format(p.pid)) 13 print("session pid which subprocess exist in: {}".format(os.getsid(p.pid))) 14 print("subprocess's group pid: {}".format(os.getpgid(p.pid))) 15 16 time.sleep(10) 17 get_cmd_pid = "pgrep '{}'".format('perf') 18 cmd_pid = os.popen(get_cmd_pid).read() 19 print("{} : {}".format(get_cmd_pid, cmd_pid)) 20 21 os.kill(p.pid, signal.SIGINT)
(1)在命令行输入:$ sudo python perf_test.py,打印如下:
sudo perf record -e cpu-clock -g -p 9621 -o perf_9621.data
cur process pid: 9621
cur process's parent process pid: 9620
subprocess pid: 9622
session pid which subprocess exist in: 22480
subprocess's group pid: 9620
pgrep 'perf' : 9624
(2)待perf_test.py运行起来后,运行结束前,在另一terminal中查看perf pid:
$ pgrep "perf"
9624
$ ps a
PID TTY STAT TIME COMMAND
9620 pts/20 S+ 0:00 sudo python perf_test.py
9621 pts/20 S+ 0:00 python perf_test.py
9622 pts/20 S+ 0:00 /bin/sh -c sudo perf record -e cpu-clock -g -p 9621 -o perf_9621.data
9623 pts/20 S+ 0:00 sudo perf record -e cpu-clock -g -p 9621 -o perf_9621.data
9624 pts/20 S+ 0:00 /usr/lib/linux-tools/4.15.0-107-generic/perf record -e cpu-clock -g -p 9621 -o perf_9621.data
9629 pts/19 R+ 0:00 ps a
22480 pts/20 Ss 0:01 bash
可见:
(a)PID9620的COMMAND恰好是(1)中命令行的输入。
(b)PID9621是perf_test.py运行时的PID,从(1)打印看即示例代码中os.getpid()的获取值。而且从(1)的打印看9620恰是9621的父PID。
(c)示例代码中使用subprocess启动了一个命令,该命令行的PID是9622,从(1)和(2)可以看到。同时从(2)可见,该命令行与命令的实际运行/内核运行都有不同的PID
(d)使用pgrep 'perf'获取的是内核运行的PID
参考: