外界调用向mgr进程发送消息,mgr根据不同消息启动或关闭相应进程(启动的进程,独占用,只启动一个);
若有进程程退出 则mgr向外界发出信号。
外界代码:
点击(此处)折叠或打开
- #!/usr/bin/python
- #
- # -*- coding:utf-8 -*-
- #
- #
- import sys
- import os
- import subprocess
- import signal
- import time
- import random
- def sig_usr1(signum, frame):
- print("recive sinal from process(exited)")
-
- signal.signal(signal.SIGUSR1, sig_usr1)
- cmds= ['./mgr.py']
- n =1
- p = subprocess.Popen( cmds,stdin=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=False)
- while True:
-
- time.sleep(1)
- ret = p.poll()
- if ret is None:
- #print("main="+str(n))
- p.stdin.write(str(n)+"\n")
- p.stdin.flush()
- p.send_signal(signal.SIGUSR1)
- n = random.randint(1, 3)
-
- print("main exit")
管理进程
- #!/usr/bin/python
- #
- # -*- coding:utf-8 -*-
- #
- import sys
- import os
- import time
- import signal
- import subprocess
- import json
- data = {'num': 0, 'error': 0}
-
- def getParentID():
- p=subprocess.Popen("ps -ef|grep tt.py|grep -v grep|awk '{print $2}'",stdout=subprocess.PIPE,shell=True)
- ret = int(p.stdout.readline())
- return ret
-
- par_id = getParentID()
- print(par_id)
- exe_process = 0
- isRuning = True
- def sig_usr1(signum, frame):
- ret = sys.stdin.readline()
- data['num'] = int(ret)
-
-
- signal.signal(signal.SIGUSR1, sig_usr1)
- while isRuning:
- time.sleep(1)
- print("data['num'] ="+str(data['num']))
- if exe_process == 0: #for open
- if data['num'] == 1:
- exe_process=subprocess.Popen("./a.out",close_fds=False)
- elif data['num'] == 2:
- exe_process=subprocess.Popen("./b.out",close_fds=False)
- else:
- continue
- else: #if exe_process == 0: for close
- ret = exe_process.poll()
- if ret is None:
- if data['num'] == 3:
- exe_process.terminate()
- exe_process = 0
- os.kill(par_id,signal.SIGUSR1)
-
- else: #if ret is None self close
- exe_process = 0
- print("end"+str(par_id))
- os.kill(par_id,signal.SIGUSR1)
-
- print "mgr process over "
python进程通讯注意问题
1)发送信号: os.kill(par_id,signal.SIGUSR1) #注意要 import os
2)subprocess结合管道要注意,不用就不要打开,否则容易出错
比如p = subprocess.Popen(cmd,stdin=subprocess.PIPE,close_fds=False)
stdin 要用到。
3)用subprocess调用Popen时候,cmd若是python脚本,要确保能编译通过并运行。则调用,否则不好排除错误
阅读(8283) | 评论(0) | 转发(0) |