Is there a way to kill a process listening on a given port (e.g. in bash lsof -t -i tcp:8000 | xargs kill) from a shell script that will also work on cygwin, as well as bash?

  • 1
    Cygwin as well as bash? Cygwin runs bash just fine. O.o – muru May 9 '15 at 8:42
  • 1
    None of those commands are part of bash. Well, the | is but that is 100% portable. What error are you getting? How does it fail? Do you have lsof and xargs installed on your Cygwin? – terdon May 9 '15 at 8:55
  • Does that scriptlet not work on cygwin? – NotFromBrooklyn May 9 '15 at 9:20
  • Right... I was not very precise: the 'lsof' command (which indeed is not bash) is found only on some "UNIX dialects" (this is the wording used by 'man lsof'). Cygwin does not recognize it as a command (while 'kill' and 'xargs' seem to be recognized). Is there an equivalent one-liner (using or not using 'kill' and 'xargs') that will achieve on Cygwin the same result as the command I mentioned in my question? – UndefinedBehavior May 11 '15 at 8:12

AFAIK, lsof has not been ported to cygwin.

You could use the Microsoft netstat utility there:

netstat -aon | awk '$1 == "TCP" && $4 == "LISTENING" && $2 ~ /:8000$/ {print $5}' |
  xargs kill
| improve this answer | |

The initial part of the problem of killing processes that are listening on a given port is identifying the process. lsof isn't available on Cygwin, but the fuser tool is (as part of the psmisc package) and is documented in its man page as:

fuser - identify processes using files or sockets

There is a demonstration in the EXAMPLES section of the manual that shows

fuser telnet/tcp shows all processes at the (local) TELNET port.

(You may need to run your cygwin shell as an administrator.)

| improve this answer | |
New contributor
David Dyck is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.