python两个程序之间的通信
用socket实现,与socket网络编程不一样的是
socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)的第一个参数是
socket.AF_UNIX而不是 socket.AF_INET
例中两个python程序 s.py/c.py 要先运行s.py
fedora13/python2.6,成功实现
s.py
#!/usr/bin/env python
import socket
import os
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
if not os.path.exists(conn):
os.mknod(conn)
if os.path.exists(conn):
os.unlink(conn)
sock.bind(conn)
sock.listen(5)
while True:
connection,address = sock.accept()
data = connection.recv(1024)
if data == "hello,server":
print "the client said:%s!\n" % data
connection.send("hello,client")
connection.close()
c.py
#!/usr/bin/env python
import socket
import time
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
sock.connect(conn)
time.sleep(1)
sock.send('hello,server')
print sock.recv(1024)
用socket实现,与socket网络编程不一样的是
socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)的第一个参数是
socket.AF_UNIX而不是 socket.AF_INET
例中两个python程序 s.py/c.py 要先运行s.py
fedora13/python2.6,成功实现
s.py
#!/usr/bin/env python
import socket
import os
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
if not os.path.exists(conn):
os.mknod(conn)
if os.path.exists(conn):
os.unlink(conn)
sock.bind(conn)
sock.listen(5)
while True:
connection,address = sock.accept()
data = connection.recv(1024)
if data == "hello,server":
print "the client said:%s!\n" % data
connection.send("hello,client")
connection.close()
c.py
#!/usr/bin/env python
import socket
import time
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
sock.connect(conn)
time.sleep(1)
sock.send('hello,server')
print sock.recv(1024)
sock.close()
转自:http://www.dengdeng.name/u/deng/archives/2011/104.html