Is there a way to kill all processes that are running in/from a certain directory?

Viewed 1199

I need a way to kill everything that are running in the current directory. I'm somewhat new to shell, so forgive me for being stupid or potentially not understanding your answers. I have a half-decent grasp, but if you'd please take the extra time to explain what exactly your solution to my problem does, it would be greatly appreciated.

3 Answers

you have to use lsof command then the argument will be the directory you want to kill the process

#!/usr/bin/env bash                                                                                                                                 
lsof $(pwd) | \                                                           
    awk -F " " ' { print $2 } ' | \                                       
    while read process ; do                                               
       [[ ${process} == "PID" ]] && continue;
          # kill the processes here
          # if you assign each process to a variable or an array
          # you will not be able to access it after leaving this while loop
          # pipes are executed as subshells
          echo ${process};                                                 
     done

The phrase 'running in' a directory might be interpreted in different ways, some of them are: (1) the program was started from this directory, (2) the program uses this directory as working directory, or (3) the program accesses this directory in any way.

Most likely you have problem (3) and the answer was already given: use

$ fuser -k

but beware, it might kill more than expected!

For problem (1) I would search the processes environment

$ grep -l "/home/username/directory" /proc/*/environ | grep -o [0-9]*

and kill the resulting processes.

lsof /path/to/directory | awk '{ print $2 }' | xargs kill

The lsof /path/to/dir command lists processes running in relation to the path. You can run this command alone on the shell to see for yourself.

The awk '{ print $2 }' part, weeds out only the PID of those processes

The xargs helps arrange the PID list into a horizontal list and then hand it over to the kill command.

Related