Forking into the background (Linux)

Olive not0read0765 at
Mon Dec 24 01:50:24 CET 2012

My goal is to write a script that 1) write something to stdout; then 
fork into the background, closing the stdout (and stderr, stdin) pipe.

I have found this answer (forking -> setsid -> forking)

However the standard output of the child is still connected to the 
terminal. I would like that if we execute a subprocess.checkprocess on 
this program,  only "I would like to see this" is captured and that the 
program terminates when the parent exits.

#! /usr/bin/python2
import os,sys,time

print "I would like to see this"
pid = os.fork()
if (pid == 0): # The first child.
     # os.chdir("/")
    # os.umask(0)
    pid2 = os.fork()
    if (pid2 == 0):  # Second child
      print "I would like not see this"
      sys.exit()    #First child exists
else:           # Parent Code
   sys.exit()   # Parent exists

More information about the Python-list mailing list