os.system() or os.execv() w/stdout redirect and PID tracking

Michael Olivier dmtech at iname.com
Fri May 7 00:32:52 EDT 1999


Gordon McMillan wrote:
> 
> Michael Olivier writes:
> 
> > What's the best way from a python program to start another program
> > in the background and: - redirect stdout/stderr to a file - get the
> > process ID of the started program.
> >
> > It seems that:
> >
> > - os.system() call can start a program in the background, but
> > doesn't return the pid (process ID) of the started program --
> > returns 0
> /snip/
> > - if I call os.fork() and then os.execv(), the pid is trackable, but
> > I don't know a way to redirect stdout/stderr
> 
> Something like this (snipped class method from working code):
> 
>  def startChild(self):
>    c2pread, c2pwrite = os.pipe()
>    self.pid = os.fork()
>    if self.pid == 0:            #Child
>      os.close(1)                        #close stdout
>      if os.dup(c2pwrite) != 1:
>        sys.stderr.write("bad write dup!\n")
>      try:
>        os.execv("/usr/local/bin/python",
>                 ("/usr/local/bin/python",
>                  "receiver.py",
>                  "%s_GATE"%self.thissite))
>      finally:
>        print "child could not start"
>        os._exit(1)
>    print "child pid =", self.pid
>    os.close(c2pwrite)

Thanks a lot, Gordon!  This really helps.  It took a little to
understand the magic hacks going on... is there any cleaner way to refer
to stdout than as '1'?  I'm also trapping stderr as '2' ... and I
modified for the output to go to a file I open instead of piped back to
the original process.

You close stdout with os.close(1) -- os.dup() then just happens to fill
in the stdout slot in the table because it's available? Scary coding if
true, but if it gets me what I need... how much can I count on this
staying the same for future Linux & Sun implementations?

--Michael




More information about the Python-list mailing list