Sample Header Ad - 728x90

Is there a clean way to `sudo pkill` processes without including the `sudo` process?

6 votes
4 answers
8753 views
I need to kill some processes that are run as sudo, matching them by full name, and count the number of original command invocations. For each process there are two processes: the command itself, and the sudo one, but I can work this around:
$ sudo -b perf record sleep 100

$ pgrep -fa '/perf record'
2245700 /usr/lib/linux-tools/.../perf record sleep 100
The problem is that when I invoke sudo pkill, it will find, kill and count itself:
$ sudo pkill -ef '/perf record' | wc -l
2
Is there a simple way for pkill not to include itself, in this case? I've tried using pid files, which could be acceptable, but the pgrep/pkill documentation is lacking, and it seems not to work in the basic form:
$ pgrep -f '/perf record' | tee /tmp/pids
$ sudo pkill -F /tmp/pids
 killed (pid 2249211)
as it will kill only the first. The documentation says:
-F, --pidfile file
              Read PID's from file.  This option is perhaps more useful for pkill than pgrep.
but it's ambiguous about the meaning of PID's.
Asked by Marcus (991 rep)
Apr 11, 2021, 09:12 PM
Last activity: Sep 3, 2022, 08:24 PM