Takeshi Patterson
Takeshi Patterson

Reputation: 1277

Is it possible to automatically close a port in use after I stop running the script?

I'm running python scripts in the terminal which use the :5000 port.

Each time I stop the script, make changes then re-run, I get a errno:48 port in use. I then have to manually find the port in use and then kill the PID before I can run the script again:

dpadmins-MacBook:microblog presentation$ ps -fa
  UID   PID  PPID   C STIME   TTY           TIME CMD
    0   326   324   0  8:48am ttys000    0:00.03 login -pf presentation
  502   330   326   0  8:48am ttys000    0:00.10 -bash
  502   854   330   0  9:37am ttys000    0:00.05 python
  502   885   330   0  9:53am ttys000    0:00.21 flask/bin/python ./run.py
  502   886   885   0  9:53am ttys000    0:01.22 /Users/presentation/Documents/webprojects/mainflask/microblog/flask/bin/python ./run.py
    0   930   330   0 10:08am ttys000    0:00.01 ps -fa

dpadmins-MacBook:microblog presentation$ kill -9 885

Is there a way around this so I don't have to run this procedure every time?

Upvotes: 0

Views: 684

Answers (2)

Rahul R Dhobi
Rahul R Dhobi

Reputation: 5816

You can use combination of kill and netstat command to kill process which are running with port 5000

kill -9 `netstat -lnp|grep :5000|awk '{ print $7}'|awk -F/ '{ print $1 }'`

Upvotes: 0

Rei
Rei

Reputation: 96

It looks like your script does not terminate as it should. Why not writing a PID file to be able to limit instances and then bail out with an error that your script is already running with PID ?

Upvotes: 1

Related Questions