socket and subprocess problem

Roy Smith roy at panix.com
Mon Dec 15 22:18:13 EST 2008


In article 
<6d3291c3-4e12-4bdd-884a-21f15f38d105 at a12g2000pro.googlegroups.com>,
 goatold at gmail.com wrote:

> In my python code I use subprocess.Popen to run and external program
> who will listen to a TCP port. And I also create a socket to connect
> to the TCP port that the external program is listening.
> I will get 'Connection refused, errno=111' when I try to
> socket.connect().

> Class a:
>   def run()
>     subprocess.Popen(..)
> Class b:
>   def run():
>     sock = socket.socket()
>     sock.connect(..)
> #################################
> test.py
> # socket connect will fail here
> a.run()
> b.run()
> ###################################
> test1.py
> if __name__ = '__main__':
>   a.run()
> 
> test2.py
> # socket will connect fine
> if __name__ = '__main__':
>   b.run

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.

The cheesy way to test this is to sleep for a second somewhere between 
a.run() and b.run().  See if that helps.

If it doesn't, then it's possible the process started by a.run() isn't 
doing what it's supposed to do.  Try running test1.py, and while it's 
running, run netstat to see if you've got something listening on the port 
you expect.



More information about the Python-list mailing list