| OLD | NEW |
| (Empty) |
| 1 #!/usr/bin/python | |
| 2 # Copyright (c) 2011 The Native Client Authors. All rights reserved. | |
| 3 # Use of this source code is governed by a BSD-style license that can be | |
| 4 # found in the LICENSE file. | |
| 5 | |
| 6 import os | |
| 7 import signal | |
| 8 import subprocess | |
| 9 import time | |
| 10 | |
| 11 # mozrunner is needed as long as we are supporting versions of Python | |
| 12 # before 2.6. | |
| 13 import mozrunner | |
| 14 | |
| 15 class BrowserProcessBase(object): | |
| 16 | |
| 17 def __init__(self, handle): | |
| 18 self.handle = handle | |
| 19 print 'PID', self.handle.pid | |
| 20 | |
| 21 def GetReturnCode(self): | |
| 22 return self.handle.returncode | |
| 23 | |
| 24 def IsRunning(self): | |
| 25 return self.handle.poll() is None | |
| 26 | |
| 27 def Wait(self, wait_steps, sleep_time): | |
| 28 self.term() | |
| 29 i = 0 | |
| 30 # subprocess.wait() doesn't have a timeout, unfortunately. | |
| 31 while self.IsRunning() and i < wait_steps: | |
| 32 time.sleep(sleep_time) | |
| 33 i += 1 | |
| 34 | |
| 35 def Kill(self): | |
| 36 if self.IsRunning(): | |
| 37 print 'KILLING the browser' | |
| 38 try: | |
| 39 self.kill() | |
| 40 # If it doesn't die, we hang. Oh well. | |
| 41 self.handle.wait() | |
| 42 except Exception: | |
| 43 # If it is already dead, then it's ok. | |
| 44 # This may happen if the browser dies after the first poll, but | |
| 45 # before the kill. | |
| 46 if self.IsRunning(): | |
| 47 raise | |
| 48 | |
| 49 class BrowserProcess(BrowserProcessBase): | |
| 50 | |
| 51 def term(self): | |
| 52 self.handle.terminate() | |
| 53 | |
| 54 def kill(self): | |
| 55 self.handle.kill() | |
| 56 | |
| 57 | |
| 58 class BrowserProcessPosix(BrowserProcessBase): | |
| 59 """ This variant of BrowserProcess uses process groups to manage browser | |
| 60 life time. """ | |
| 61 | |
| 62 def term(self): | |
| 63 os.killpg(self.handle.pid, signal.SIGTERM) | |
| 64 | |
| 65 def kill(self): | |
| 66 os.killpg(self.handle.pid, signal.SIGKILL) | |
| 67 | |
| 68 | |
| 69 def RunCommandWithSubprocess(cmd, env=None): | |
| 70 handle = subprocess.Popen(cmd, env=env) | |
| 71 return BrowserProcess(handle) | |
| 72 | |
| 73 | |
| 74 def RunCommandWithMozrunner(cmd, env=None): | |
| 75 handle = mozrunner.run_command(cmd, env=env) | |
| 76 return BrowserProcess(handle) | |
| 77 | |
| 78 | |
| 79 def RunCommandInProcessGroup(cmd, env=None): | |
| 80 def SetPGrp(): | |
| 81 os.setpgrp() | |
| 82 print 'I\'M THE SESSION LEADER!' | |
| 83 handle = subprocess.Popen(cmd, env=env, preexec_fn=SetPGrp) | |
| 84 return BrowserProcessPosix(handle) | |
| 85 | |
| OLD | NEW |