Firefox的工作方式是:第一个实例创建一个套接字文件(或Windows上的命名管道)。这既是Firefox的下一个实例检测并与第一个实例通信,又是在死之前将URL转发给它的一种方式。套接字文件或命名管道只能从本地系统上运行的进程访问(就像文件一样),没有网络客户端可以访问它。由于它们是文件,因此防火墙也不会阻止它们(就像在文件上写入文件一样)。
这是一个天真的实现,以说明我的观点。首次启动时,将lock.sock
创建套接字文件。脚本的进一步启动将检测到锁并将URL发送给它:
import socket
import os
SOCKET_FILENAME = 'lock.sock'
def server():
print 'I\'m the server, creating the socket'
s = socket.socket(socket.AF_UNIX, socket.soCK_DGRAM)
s.bind(SOCKET_FILENAME)
try:
while True:
print 'Got a URL: %s' % s.recv(65536)
except KeyboardInterrupt, exc:
print 'Quitting, removing the socket file'
s.close
os.remove(SOCKET_FILENAME)
def client():
print 'I\'m the client, opening the socket'
s = socket.socket(socket.AF_UNIX, socket.soCK_DGRAM)
s.connect(SOCKET_FILENAME)
s.send('http://stackoverflow.com')
s.close()
def main():
if os.path.exists(SOCKET_FILENAME):
try:
client()
except (socket.error):
print "Bad socket file, program closed unexpectedly?"
os.remove(SOCKET_FILENAME)
server()
else:
server()
main()
您应该实现一个适当的协议(例如,发送适当的数据报而不是硬编码长度),也许使用SocketServer,但这超出了这个问题。在Python的Socket编程HOWTO也可能帮助你。我没有可用的Windows计算机,因此我无法确认它是否可以在该平台上运行。