我正在尝试在 C 可执行文件和 python 脚本之间建立通信管道。下面是 Python 脚本,奇怪的地方如下。如果我按如下方式运行 python 脚本,则 C 可执行文件永远不会在套接字上看到任何数据。
但是,如果我取消注释 Reader 类(即,仅启用对套接字的写入),则 C 可执行文件总是接收套接字上的数据。有没有人解释为什么当 Reader 和 Writer 线程同时运行时这不起作用?
class Reader(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def run(self):
while True:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
nonce = s.recv(4)
s.close
if len(nonce) == 4:
print("Result received \n")
class Writer(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
while True:
payload = "Hello World"
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
s.send(payload)
s.close()
reader = Reader()
writer = Writer()
reader.start()
writer.start()
try:
while True:
sleep(10000)
except KeyboardInterrupt:
print("Terminated")
编辑:
正如建议的那样,我正在尝试如下全局打开连接,但这给我带来了两个额外的问题:
1)发送数据后,Python端应该只收到4个字节,但似乎我收到了无穷无尽的数据流......
2)我在哪里可以关闭这个全局打开的流?
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
class Reader(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def run(self):
while True:
nonce = s.recv(4)
if len(nonce) == 4:
print("Result received \n")
class Writer(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
while True:
payload = "Hello World"
s.send(payload)
reader = Reader()
writer = Writer()
reader.start()
writer.start()
try:
while True:
sleep(10000)
except KeyboardInterrupt:
print("Terminated")