ActiveState Code

Recipe 186101: Really closing stdin, stdout, stderr


When creating daemons on Unix-like systems, it's typical to close or redirect stdin, stdout, and stderr. This simple recipe demonstrates that it's not quite as obvious as it might first appear.

Python
1
2
3
4
5
6
7
8
9
# here's the obvious part!
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()

# this is pretty obscure!
os.close(0)
os.close(1)
os.close(2)

Discussion

When would you want to use this? If you have a daemon process and really want to close or redirect the standard file descriptors, you must close or redirect at both the Python and C levels. Consider starting a daemon while ssh'd into a server:

% (mydaemon.py When would you want to use this?  If you have a daemon process and really

want to close or redirect the standard file descriptors, you must close or redirect at both the Python and C levels. Consider starting a daemon while ssh'd into a server:

% (mydaemon.py

Comments

  1. 1. At 12:10 a.m. on 27 mar 2003, Mike Brown said:

    ? Uh, where's the rest of the explanation?

Sign in to comment