Python守护进程以及命令行启动停止

本文介绍了一个使用Python编写的简单进程监控脚本,该脚本能启动、停止和重启指定数量的子进程,并记录操作日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/python

#coding=utf-8

import sys

import os

import time

import signal

 

Max_process = 2

log_index = 0

    

 

def start():

    global Max_process

    global log_index    

    #获取当前路径

    path = os.popen('pwd').readlines()[0]

    

    while(1):

        processInfo = os.popen('ps -ef | grep tt.py | grep -v grep').readlines()

        processNum = len(processInfo)

        if(processNum

            os.system('cd '+path)

            os.system('nohup python tt.py &')

            log_index = log_index + 1

            time.sleep(5)

 

def stopChicd():

    processInfo = os.popen("ps -ef|grep tt.py|grep -v grep|awk '{print $2}'").readlines()

    for pid in processInfo:

        os.kill(int(pid),signal.SIGKILL)

    

def stopParent():

    parentList = os.popen("ps -ef|grep Monitor.py|grep -v grep|awk '{print $2}'").readlines()

    for pid in parentList:

        os.kill(int(pid),signal.SIGKILL)

 

#杀掉除了自己所有的进程

def stopParent2():

    index = 0

    parentList = os.popen("ps -ef|grep Monitor.py|grep -v grep|awk '{print $2}'").readlines()

    for pid in parentList:

        index = index+1

        if(index

            os.kill(int(pid),signal.SIGKILL)

        

    

def stopAll():

    stopChicd()

    stopParent()

        

        

    

try:

    fun = sys.argv[1]

except Exception:

    fun = ''

if(fun == 'start'):

    start()

if(fun == 'stop'):

    stopAll()

if(fun == 'restart'):

    stopChicd()

    stopParent2()

    time.sleep(1)

    start()

 

 

 

调用的时候 python Monitor.py start|stop|restart即可

转载于:https://my.oschina.net/zfschool/blog/788530

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值