1

I'm writing a Python program for Linux and the program basically uses the terminal give feedback on it's initialization to the user and then it must relinquish control of the terminal and continue it's execution on the background. How can I achieve this?

Thank you

Raphael
  • 7,972
  • 14
  • 62
  • 83
  • 1
    You could just run your script like this: `python script.py &` or daemonize the process using the answers in this question: http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python – Collin Apr 07 '12 at 01:58

3 Answers3

2

You can use os.fork() to create a child process:

import os
import time

msg =  raw_input("Enter message for child process")

x = os.fork()

if not x:
    for i in range(5):
        time.sleep(3)
        print msg

os.fork() returns 0 in the child process, and the child process ID in the paret process Note that each process gets its own copy of local variables.

Hope this helps

Krzysztof Rosiński
  • 1,488
  • 1
  • 11
  • 24
1

Just wrap your program with python-daemon.

JBernardo
  • 32,262
  • 10
  • 90
  • 115
1

Forking is probably the Right Thing To Do, here, and daemonising better, but a simple way to get mostly the same effect, without changing the script is (as the comment on the question suggests) to simply put the script in the background.

What & won't do, however, is fully relinquish the connection to the terminal. For that, use nohup:

(nohup python foo.py >foo-output &)

is a simple way of daemonising a script. The nohup means that the process won't be killed when its controlling terminal goes, and putting the script into the background of a subshell (...), which then exits, means that it ends up as the child of the init process. That's most of what 'daemonising' means, in effect.

This is a more general technique than the original question really calls for, but it's useful nonetheless.

Norman Gray
  • 11,978
  • 2
  • 33
  • 56