calling a program without waiting for it to finish

Donn Cave donn at drizzle.com
Thu Mar 20 23:29:08 EST 2003


Quoth Alex Martelli <aleax at aleax.it>:
...
| You can take specific, platform-dependent action to terminate such
| processes in a function run at your Python program's termination
| (see standard library module atexit).  E.g., killall will work on some
| systems for such purposes.

For example,

  #!/usr/local/bin/python
  import os
  import signal
  import time

  os.spawnv(os.P_NOWAIT, '/bin/ping', ['ping', 'www.python.org'])
  time.sleep(5)
  signal.signal(signal.SIG_IGN, signal.SIGHUP)
  os.kill(-os.getpid(), signal.SIGHUP)

Notes:
-  spawnv() invokes the specified command directly without a shell,
   which is particularly advantageous when the command is calculated
   from input data and therefore not reliably safe from shellisms
   that could radically affect your command.
-  The above works only when the python script was started directly
   from an interactive shell, in which case (assuming Berkeley job
   control) it will be a process group leader - running in its own
   process group, with process group ID == process ID.  Any process
   forked by the python script will belong to that same process group.
-  kill(-n, x) means send signal x to process group n.  I expect that
   may be enshrined in POSIX 1003.1, don't know for sure though.
-  signal(SIG_IGN,) is to survive my own signal.
-  You can use setpgrp() to effect more elaborate process control,
   but not often will it be worth the trouble.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list