外界調用向mgr進程發送消息,mgr根據不一樣消息啓動或關閉相應進程(啓動的進程,獨佔用,只啓動一個);python
如有進程程退出 則mgr向外界發出信號。shell
外界代碼:json
#!/usr/bin/pythondom
#進程
# -*- coding:utf-8 -*-utf-8
#ci
#get
import syscmd
import osit
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腳本,要確保能編譯經過並運行。則調用,不然很差排除錯誤