I need to have several processes coordinated with each other on a machine such that each process chooses a different port for creating a socket to communicate with a different machine. Each process must choose a port number from a range of available ports such that at any point in time only one process is using a given port number.
Is there an existing mechanism to do this coordination or do I need to build my own?
Presently, I am using a file on disk to register the port number and the PID that is using that port. If an entry is found where there is no PID running anymore, the entry is removed as the process is assumed to have exited non-gracefully and thus the entry needs to be reaped.
However, I seem to have some kind of race condition as in rare instances, I end up with two processes using the same port and the second process does not see the file contents showing the port reserved and ends up using it a second time.
Rather than fix this, I'd rather adopt an existing mechanism for this collision avoidance of ports, so I'm asking if such a utility already exists.