Raphael
Raphael

Reputation: 8192

How to make the program relinquish control of the terminal?

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

Upvotes: 1

Views: 282

Answers (3)

Norman Gray
Norman Gray

Reputation: 12514

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.

Upvotes: 1

Krzysztof Rosiński
Krzysztof Rosiński

Reputation: 1478

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

Upvotes: 2

JBernardo
JBernardo

Reputation: 33407

Just wrap your program with python-daemon.

Upvotes: 1

Related Questions