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.openvpn_api = None
self.name = name
self.pid_fp = None
if loop:
self.loop = loop
else:
@ -75,7 +76,7 @@ class Openvpn:
if self.status == IDLE:
self.status = RUNNING
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))
def get_log(self):
@ -93,7 +94,7 @@ class Openvpn:
async def stop(self):
if self.status == RUNNING:
try:
self.proc.kill()
os.kill(self.PID)
except Exception as err:
print("kill failed:", err)
@ -110,15 +111,35 @@ class Openvpn:
while self.status == RUNNING:
print("create proc")
print(self.status)
proc = await asyncio.create_subprocess_exec(
"sg", group, "-c", cmd,
self.pid_fp = os.path.join(self.folder_path, "pid.txt")
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,
stderr=asyncio.subprocess.PIPE)
print("started")
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(
'localhost', int(self.management_port))
print(f"pid: {proc.pid}")
print(f"pid: {self.PID}")
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout: