David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 1 | # spawn - This is ugly, OS-specific code to spawn a separate process. It |
| 2 | # also defines a function for getting the version of a path most |
| 3 | # likely to work with cranky API functions. |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | def hardpath(path): |
| 8 | path = os.path.normcase(os.path.abspath(path)) |
| 9 | try: |
| 10 | import win32api |
| 11 | path = win32api.GetShortPathName( path ) |
| 12 | except: |
| 13 | pass |
| 14 | return path |
| 15 | |
| 16 | if hasattr(os, 'spawnv'): |
| 17 | |
| 18 | # Windows-ish OS: we use spawnv(), and stick quotes around arguments |
| 19 | # in case they contains spaces, since Windows will jam all the |
| 20 | # arguments to spawn() or exec() together into one string. The |
| 21 | # kill_zombies function is a noop. |
| 22 | |
| 23 | def spawn(bin, *args): |
| 24 | nargs = [bin] |
| 25 | for arg in args: |
| 26 | nargs.append( '"'+arg+'"' ) |
| 27 | os.spawnv( os.P_NOWAIT, bin, nargs ) |
| 28 | |
| 29 | def kill_zombies(): pass |
| 30 | |
| 31 | elif hasattr(os, 'fork'): |
| 32 | |
| 33 | # UNIX-ish operating system: we fork() and exec(), and we have to track |
| 34 | # the pids of our children and call waitpid() on them to avoid leaving |
| 35 | # zombies in the process table. kill_zombies() does the dirty work, and |
| 36 | # should be called periodically. |
| 37 | |
| 38 | zombies = [] |
| 39 | |
| 40 | def spawn(bin, *args): |
| 41 | pid = os.fork() |
| 42 | if pid: |
| 43 | zombies.append(pid) |
| 44 | else: |
| 45 | os.execv( bin, (bin, ) + args ) |
| 46 | |
| 47 | def kill_zombies(): |
| 48 | for z in zombies[:]: |
| 49 | stat = os.waitpid(z, os.WNOHANG) |
| 50 | if stat[0]==z: |
| 51 | zombies.remove(z) |
| 52 | |
| 53 | else: |
| 54 | # If you get here, you may be able to write an alternative implementation |
| 55 | # of these functions for your OS. |
| 56 | |
| 57 | def kill_zombies(): pass |
| 58 | |
| 59 | raise OSError, 'This OS does not support fork() or spawnv().' |