python 守护程序检测进程是否存在_python创建守护进程的疑问

我自己写了一个简易的下载和文件执行的客户端,如下

"""

省略若干代码

"""

#执行下载函数

def do_script():

"""Start working"""

script_list = None

for mark in range(3):

try:

# get scripts

if not script_list:

script_list = get_scripts()

if script_list == None:

continue

for script in script_list:

command_exec = 'chmod a+x %s' % script

PyShell.new_progress(command_exec)

PyShell.new_progress('./%s' % script)

# return

except Exception as e:

logging.info(traceback.format_exc())

if mark == 2:

send_error_log(e)

#创建守护进程

def createDaemon():

try:

if os.fork() > 0: os._exit(0)

except OSError, error:

print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)

os._exit(1)

os.chdir('/')

os.setsid()

os.umask(0)

try:

pid = os.fork()

if pid > 0:

#print 'Daemon PID %d' % pid

os._exit(0)

except OSError, error:

#print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)

os._exit(1)

sys.stdout.flush()

sys.stderr.flush()

si = file("/dev/null", 'r')

so = file("/dev/null", 'a+')

se = file("/dev/null", 'a+', 0)

os.dup2(si.fileno(), sys.stdin.fileno())

os.dup2(so.fileno(), sys.stdout.fileno())

os.dup2(se.fileno(), sys.stderr.fileno())

#写pid文件

if os.path.exists(pidfile):

os.remove(pidfile)

pid = str(os.getpid())

file(pidfile, 'w+').write("%s\n" % pid)

#为什么执行函数不能写这里,写这里会导致代码无法执行到这里?

if __name__ == '__main__':

if platform.system() == "Linux":

createDaemon()

#必须写到main里,才可以执行?

while 1:

do_script()

time.sleep(20)

else:

os._exit(0)

其中,为什么执行函数不能写在守护进程函数里,而必须写到main函数里呢?

难道是因为守护进程函数里无法再创建进程原因?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值