发布网友 发布时间:2022-04-20 20:25
共1个回答
热心网友 时间:2022-04-18 10:10
import os,sys,commands,time
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
"""set daemonize """
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed (%d) %s\n " %(e.errno, e.strerror))
sys.exit(0)
os.setsid()
os.chdir('.')
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed (%d) %s\n " %(e.errno, e.strerror))
sys.exit(0)
if not stderr: stderr = stdout
si = file(stdin, "r")
so = file(stdout, "w+")
se = file(stderr, "a+")
pid = str(os.getpid())
print "start with pid :[%s]" % pid
fp = open("pid","w")
print >> fp, pid
fp.close()
sys.stderr.flush()
sys.stdout.flush()
sys.stderr.flush()
os.p2(si.fileno(), sys.stdin.fileno())
os.p2(so.fileno(), sys.stdout.fileno())
os.p2(se.fileno(), sys.stderr.fileno())
def main():
daemonize(stdout='test.log', stderr='test.log')
cmd = "ls"
while 1:
(status, ret) = commands.getstatusoutput(cmd)
print status
print ret
time.sleep(10)
if __name__ == "__main__":
main()
你可以尝试照这个写写,基本的元素都齐了,后台运行,执行shell命令
不过如果只是想要后台的话,直接shell后台执行一下也就可以了