- OS Environment: Pfsense 2.4.4 based on FreeBSD 11.2-RELEASE-p10
- Python: Python 2.7.16 (default, May 10 2019, 17:54:37)
- Problem description:
I want to set my first python script running as a daemon, and I define a function:
def set_daemon(cur_woring_path):
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
print "First fork failed:%s" % e.message
sys.exit(1)
os.chdir(cur_woring_path)
os.setsid()
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
print "Second fork failed:%s" % e.message
sys.exit(1)
os.close(sys.stdin.fileno())
os.close(sys.stdout.fileno())
os.close(sys.stderr.fileno())
After I called set_daemon(...)
, I wan to execute shell command and get the output:
load_logger_config("INFO")
logger = logging.getLogger("debug_info_logger")
target_process_name = "my_second_process.py"
set_daemon("/root")
cmd = "ps -aux | grep " + target_process_name + "| grep -v grep|awk -F \" \" '{print $2}' "
out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
logger.warning("Found process is running..., pid = %s", out.stdout.read()[:-1])
But the out
string is always empty, I have tried:
commands.getoutput(cmd)
os.popen(cmd)
popen2
redirect to file is empty too.
cmd = "ps -aux | grep " + target_process_name + "| grep -v grep|awk -F \" \" '{print $2}' > tmp.txt"
...
Cause of the problem maybe:
os.close(sys.stdin.fileno())
os.close(sys.stdout.fileno())
os.close(sys.stderr.fileno())
because without set_daemon
, everything is ok.
I've searched google, but nothing help.
Are there any solutions? I need both set_daemon
and shell output
, could I reopen the stdout fileno? I appreciate a lot anyone could help me