workaround to get pid

This commit is contained in:
mantaohuang 2020-04-03 22:25:01 -04:00
parent a9f72f53ac
commit 43ac20cc38

View File

@ -47,6 +47,7 @@ class Openvpn:
self.run_task = None self.run_task = None
self.openvpn_api = None self.openvpn_api = None
self.name = name self.name = name
self.pid_fp = None
if loop: if loop:
self.loop = loop self.loop = loop
else: else:
@ -75,7 +76,7 @@ class Openvpn:
if self.status == IDLE: if self.status == IDLE:
self.status = RUNNING self.status = RUNNING
config_fp = self.generate_config_file() config_fp = self.generate_config_file()
cmd = " ".join(["", "openvpn", "--config", config_fp]) cmd = " ".join(["openvpn", "--config", config_fp])
self.run_task = self.loop.create_task(self.run(cmd)) self.run_task = self.loop.create_task(self.run(cmd))
def get_log(self): def get_log(self):
@ -93,7 +94,7 @@ class Openvpn:
async def stop(self): async def stop(self):
if self.status == RUNNING: if self.status == RUNNING:
try: try:
self.proc.kill() os.kill(self.PID)
except Exception as err: except Exception as err:
print("kill failed:", err) print("kill failed:", err)
@ -110,15 +111,35 @@ class Openvpn:
while self.status == RUNNING: while self.status == RUNNING:
print("create proc") print("create proc")
print(self.status) print(self.status)
proc = await asyncio.create_subprocess_exec( self.pid_fp = os.path.join(self.folder_path, "pid.txt")
"sg", group, "-c", cmd, try:
os.remove(self.pid_fp)
except:
pass
shell = f"sg {group} -c \"echo \\$\\$ > {self.pid_fp}; {cmd}\""
print(shell)
proc = await asyncio.create_subprocess_shell(
shell,
stdout=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE) stderr=asyncio.subprocess.PIPE)
print("started")
self.proc = proc self.proc = proc
self.PID = proc.pid for i in range(3):
await asyncio.sleep(1)
got_pid = False
try:
self.PID = open(self.pid_fp, "r").read()
got_pid = True
except:
got_pid = False
if got_pid:
break
if not got_pid:
print("error, cannot get pid")
break
self.openvpn_api = openvpn_api.VPN( self.openvpn_api = openvpn_api.VPN(
'localhost', int(self.management_port)) 'localhost', int(self.management_port))
print(f"pid: {proc.pid}") print(f"pid: {self.PID}")
stdout, stderr = await proc.communicate() stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]') print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout: if stdout: