socket and subprocess problem
Bryan Olson
fakeaddress at nowhere.org
Tue Dec 16 01:44:12 EST 2008
goatold at gmail.com wrote:
> Guys thanks to point it out.
> Yes, it's a race problem. I tried sleep long enough, then I can
> connect to the socket. I should add code to try to connect to the
> socket for a given time out.
As Roy noted, that's "the cheesy way". Are the kind of programmers who
accept cheesy solutions? Of course not.
The right solution is for the child process to tell the parent when the
port is ready for connections. There are a variety of ways to transfer
that message; the most straightforward is for the child process to write
something to its standard output.
Parent process:
Launch child.
read() child's output, waiting for the ready message.
connect() to the port the child established.
Child process:
Create the socket; bind(); listen().
Write the ready message to stdout.
accept().
There's a subtle yet important point here, that frequently gets lost:
Roy Smith wrote:
>> Sounds like a timing problem. I assume that the process started by a.run()
>> creates a socket and does a bind/listen/accept sequence on it. The problem
>> is, there's nothing in your code which guarantees that this happens before
>> b.run() executes the connect() call.
Actually, it's just bind() and listen() that have to happen before the
client can connect(); accept() will not succeed until after a client
connects. In our example the child process is the server, and the
server's readiness alert should go after his call to listen() returns,
but before he calls accept().
--
--Bryan
More information about the Python-list
mailing list