-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommunicate.py
More file actions
64 lines (54 loc) · 2.1 KB
/
communicate.py
File metadata and controls
64 lines (54 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import subprocess
class Communication:
def __init__(self, checker, source):
self.checker = checker
self.source = source
self.log = open("./communication.log", "w+")
def eof(self, buffer, end):
if(buffer.strip() in end):
self.log.writelines(f"End the communication after receive \'{buffer.strip()}\'.\n")
return True
return False
def communicate(self, end, source_first = False):
checker_process = subprocess.Popen(self.checker, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
source_process = subprocess.Popen(self.source, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
#Start communation
self.log.writelines("Start communication:\n\n")
while True:
if(source_first): #source go first
buffer = source_process.stdout.readline().decode()
source_process.stdout.flush()
self.log.writelines(f"Source: {buffer.strip()}\n")
checker_process.stdin.write(buffer.encode())
checker_process.stdin.flush()
if self.eof(buffer, end) : break
source_first ^= True
else:
buffer = checker_process.stdout.readline().decode()
checker_process.stdout.flush()
self.log.writelines(f"Checker: {buffer.strip()}\n")
source_process.stdin.write(buffer.encode())
source_process.stdin.flush()
if self.eof(buffer, end) : break
source_first ^= True
#End communation and kill process
self.log.writelines("\n")
checker_process.stdin.close()
checker_process.stdout.close()
checker_status = checker_process.wait()
if checker_status != 0:
self.log.writelines("There are some error when kill checker process.")
raise Exception(checker_status)
else:
self.log.writelines("Killed checker process successfully.\n")
source_process.stdin.close()
source_process.stdout.close()
source_status = source_process.wait()
if source_status != 0:
self.log.writelines("There are some error when kill source process.")
raise Exception(source_status)
else:
self.log.writelines("Killed source process successfully.")
if __name__ == '__main__':
communication = Communication('a.exe', 'b.exe')
communication.communicate('')