unixkilllsof

Unix: How to kill a list of processes (PID) based on the lsof command?


I would like to kill a list of PID that correlates to a process in a tcsh shell. I ran the following command:

> losf <file> | awk '{print($2)"'

The command will show a list of PIDs.

pid1

pid2

...

I then ran the following command to kill those PIDs.

> kill -9 `lsof <file> | awk'{print($2)}'`

When the kill command is executed, the terminal just somehow hanged without killing any PID. I then had to revert to killing those PID one by one.

Therefore, is there a way to do what I intended to do as illustrated above? Thank you.


Solution

  • xargs is a standard utility for performing action on each given line read from standard input. You could use it like this:

    > lsof <file> | awk '{print($2)}' | xargs -I '{}' kill {}