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.
Roy Smith wrote: > In article > <6d3291c3-4e12-4bdd-884a-21f15f38d...@a12g2000pro.googlegroups.com>, > goat...@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. -- http://mail.python.org/mailman/listinfo/python-list