title: Output redirect with fork&execvp
body: <p>I have a program that prints output to stdout:</p>
  
  <pre><code>#!/usr/bin/env python
  
  import time
  import sys
  
  if len(sys.argv) &lt; 1:
      valualuee = 1
  else:
      value = sys.argv[1]
  
  counter = 0
  while counter &lt; 100:
      print value
      time.sleep(0.1)
      counter = counter+1
  </code></pre>
  
  <p>Then I want at program that executes 2 instances of it with different arguments.
  In that program I want to specify in which file that program's stdout is redirected.</p>
  
  <p>After both programs have finished, I want to print something again in the main console, which fails.</p>
  
  <p>I also want to be able to see one program's output on the console in addition to its output in the file.</p>
  
  <p>This is my try:</p>
  
  <pre><code>#!/usr/bin/env python
  
  import subprocess
  import sys
  import os
  import time
  
  ###########################################
  def background(program, argument, logfile):
      #redirect stdout
      sys.stdout = open(logfile, "w")
      os.dup2(sys.stdout.fileno(), 1)
  
      try:
          pid=os.fork()
      except OSError, e:
          sys.exit(1)
  
      if pid==0:  #in the forked process
          ex = "./" + program
          os.execvp(ex, [ex, argument])
  
      return pid
  ###########################################
  
  
  pid1 = background("program1.py", "1", "log1")
  pid2 = background("program1.py", "2", "log2")
  
  os.waitpid(pid1, 0)
  os.waitpid(pid2, 0)
  
  #print in console again
  print "done"
  </code></pre>