satoru
satoru

Reputation: 33215

How to get a socket FD according to the port occupied in Python?

In my program, A serve-forever daemon is restarted in a subprocess.

The program itself is a web service, using port 5000 by default.

I don't know the detail of the start script of that daemon, but it seems to inherit the socket listening on port 5000.

So if I were to restart my program, I'll find that the port is already occupied by the daemon process.

Now I am considering to fine tune the subprocess function to close the inherited socket FD, but I don't know how to get the FD in the first place.

Upvotes: 0

Views: 560

Answers (2)

jfs
jfs

Reputation: 414079

There is close_fds parameter (subprocess.Popen) that is safe to set to True on Unix (it is default on Python 3). Though you shouldn't need it: a proper daemon should close all open file descriptors itself before forking.

Unrelated: if you want your program to be able to restart during the TIME_WAIT period; set SO_REUSEADDR socket option.

Upvotes: 1

peterruijter
peterruijter

Reputation: 11

It seems like a permission issue. The subprocess is probably running as an other user and therefore you will not have access to the process. Use sudo ps xauw |grep [processname] to figure as under what user the daemon process is running.

Upvotes: 1

Related Questions