Linux: How to kill a process using its listening port or used files!
To kill a Linux process you need to know either its PID or the process name, but there is also another way not so well known but still very…
To kill a Linux process you need to know either its PID or the process name, but there is also another way not so well known but still very effective: to kill a process using its listening port or a used file! lets see how we can do this!
I guess most people do the same like me, search for the PID using ps aux and grep
$ ps aux | grep -i nginx
root 332640 0.0 0.0 55208 12012 ? S 16:52 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data 332642 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332643 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332644 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332645 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332646 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332647 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332648 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker process
www-data 332649 0.0 0.0 55844 5524 ? S 16:52 0:00 nginx: worker processand then kill the process
$ sudo kill -9 332640But this requires two steps, to find the process and then kill it! using the fuser command this can be consolidated to a single command by passing only the listening port!
The following command sends a kill signal to the PID listening to port 80, which in this case is nginx
$ sudo fuser -k 80/tcp
80/tcp: 337277 337278 337279 337280 337281 337282 337283 337284 337285Using this command we killed nginx, lets see know how we can do the same using a file that we know that is open by a process
$ sudo fuser -a -k /var/log/nginx/access.log
/var/log/nginx/access.log: 346098 346099 346100 346101 346102 346103 346104 346105 346106The above command killed all processes that currently where using the access.log of nginx.
Note: if you have two different processes working on a file for example nginx and vim will kill both!
Conclusion
The fuser command can be used to identify which processes are using a particular file, directory, or socket. It can also be used to terminate those processes. It is a powerful tool that can be used to troubleshoot problems related to file, directory, or socket usage.