Suresh
Suresh

Reputation: 967

xmlrpc - dynamically choosing port number

I have a python program which starts another executable as a subprocess. The sub-process, in turn, starts an XML-RPC server to which the parent process connects as a client.

I don't want to fix the port number as sometimes the port might not be available because of another instance of the same program being run on the same machine.

I can leave it to the parent process to choose the port number and pass that information as an argument or through Unix environment variable.

But in the worst case there is a possibility that the port number became unavailable from the time parent checked and then sub-proc tried to acquire.

We can let the sub proc first acquire the port number and then tell it to the parent. The sub-process prints a huge amount of data which is redirected to a file. Is there any better way than having to parse the stdout? something like the Unix Env variable but modifying the caller's environment.

Another way is for the parent to have an xml-rpc server and pass on the address to the sub proc. The sub proc would make a call and inform what is its server's address.

Is there any better way?

Upvotes: 0

Views: 1057

Answers (1)

Steven Du
Steven Du

Reputation: 1691

Not sure your OS, if it is ubuntu, then your parent could find the port by using child processid and netstat.

netstat -antlp | grep processid

Another way by read stdout from sub process:

#parent
import subprocess

proc=subprocess.Popen(['./test_python_xmlrpc_server.py'], stdout=subprocess.PIPE,close_fds=True)

line = proc.stdout.readline()
print line

And the child process, using a port of 0 so a free port with be chosen. Then print out the port:

#!/usr/bin/python    
#./test_python_xmlrpc_server.py 
from SimpleXMLRPCServer import SimpleXMLRPCServer
    
server = SimpleXMLRPCServer(("0.0.0.0", 0)) #pick a free port
print server.server_address
#
#

REF:

How to kill a process on a port on ubuntu

Stop reading process output in Python without hang?

xmlrpc getting auto-assigned server port number

Upvotes: 1

Related Questions