Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/interfaces/cleaner.py
8814 views
1
"""
2
Interface to the Sage cleaner
3
4
Triva Note: For the name "sage-cleaner", think of the
5
"The Cleaner" from Pulp Fiction:
6
http://www.frankjankowski.de/quiz/illus/keitel.jpg
7
"""
8
9
#*****************************************************************************
10
# Copyright (C) 2007 William Stein <[email protected]>
11
#
12
# Distributed under the terms of the GNU General Public License (GPL)
13
# as published by the Free Software Foundation; either version 2 of
14
# the License, or (at your option) any later version.
15
# http://www.gnu.org/licenses/
16
#*****************************************************************************
17
18
import os
19
20
from sage.misc.misc import SAGE_TMP
21
22
def cleaner(pid, cmd=''):
23
"""
24
Write a line to the ``spawned_processes`` file with the given
25
``pid`` and ``cmd``.
26
"""
27
if cmd != '':
28
cmd = cmd.strip().split()[0]
29
# This is safe, since only this process writes to this file.
30
F = os.path.join(SAGE_TMP, 'spawned_processes')
31
try:
32
with open(F, 'a') as o:
33
o.write('%s %s\n'%(pid, cmd))
34
except IOError:
35
pass
36
else:
37
start_cleaner()
38
39
40
def start_cleaner():
41
"""
42
Start ``sage-cleaner`` in a new process group.
43
"""
44
if not os.fork():
45
os.setpgid(os.getpid(), os.getpid())
46
47
# Redirect stdin, stdout, stderr to /dev/null
48
with open(os.devnull, "r+") as f:
49
os.dup2(f.fileno(), 0)
50
os.dup2(f.fileno(), 1)
51
os.dup2(f.fileno(), 2)
52
53
# Close all other file descriptors
54
try:
55
maxopenfiles = os.sysconf("SC_OPEN_MAX")
56
if maxopenfiles <= 0:
57
raise ValueError
58
except ValueError:
59
maxopenfiles = 1024
60
os.closerange(3, maxopenfiles)
61
62
os.execlp("sage-cleaner", "sage-cleaner")
63
64