- 论坛徽章:
- 0
|
父进程创建子进程,然后父子间使用multiprocessing.Queue()来进行通信。
首先子进程退出,关闭Queue,然后父进程也关闭Queue.
这时,使用命令lsof -c python3|egrep 'pipe|sem' ,会发现有pipe和sem似乎没被关闭,这是怎么回事?并且,每多创建一个子进程然后退出,就会有越来越多的pipe和sem句柄存留。求教怎么彻底关闭这些句柄,谢谢。
测试代码如下:
import os,sys,time,multiprocessing,queue,threading,signal
pdict = {}
def child(name,req):
while True:
ret = 'a'
try:
ret = req.get(timeout=5)
print("%s get %s" %(name,ret))
time.sleep(10)
msg = "%s exit now" %(name)
print(msg)
time.sleep(1)
req.close()
del req
os._exit(4)
except Exception as e:
print("child err,%s" %str(e))
def start_child(name,req):
print("to start %s now" %name)
p = multiprocessing.Process(target=child, args=(name,req) )
p.start()
pdict[name] = [req,p]
def main():
print(" main start now")
req = ''
count = 0
signal.signal(signal.SIGCHLD,signal.SIG_IGN)
while True:
count = 0
while True:
count = count + 1
name = "child#%s" %count
req = multiprocessing.Queue()
print("\n")
print("start %s child now ......" %name)
p1 = threading.Thread( target=start_child,args = (name,req))
p1.start()
req.put([count])
time.sleep(13)
rq = pdict[name][0]
p = pdict[name][1]
rq.close()
rq.close()
del rq
print("clear %s resource\n" %name)
time.sleep(20)
print(" begin the %s round now #################" %(count+1))
if __name__ == "__main__":
main()
随着子进程的创建退出,lsof显示如下:
第一个子进程创建后退出:
[root@Steve ~]# lsof -c python3|egrep 'pipe|sem'
python3 5135 root DEL REG 0,16 18198145 /dev/shm/sem.rBbhHD
python3 5135 root DEL REG 0,16 18198144 /dev/shm/sem.Z4yneZ
python3 5135 root DEL REG 0,16 18198143 /dev/shm/sem.DnUuLk
python3 5135 root 5r FIFO 0,8 0t0 18198146 pipe
第二个子进程创建后退出:
[root@Steve ~]# lsof -c python3|egrep 'pipe|sem'
python3 5135 root DEL REG 0,16 18203718 /dev/shm/sem.1pq5ru
python3 5135 root DEL REG 0,16 18203717 /dev/shm/sem.B2iNRc
python3 5135 root DEL REG 0,16 18203716 /dev/shm/sem.xu6vhV
python3 5135 root DEL REG 0,16 18198145 /dev/shm/sem.rBbhHD
python3 5135 root DEL REG 0,16 18198144 /dev/shm/sem.Z4yneZ
python3 5135 root DEL REG 0,16 18198143 /dev/shm/sem.DnUuLk
python3 5135 root 5r FIFO 0,8 0t0 18198146 pipe
python3 5135 root 6r FIFO 0,8 0t0 18203719 pipe
第三个子进程创建后退出:
[root@Steve ~]# lsof -c python3|egrep 'pipe|sem'
python3 5135 root DEL REG 0,16 18209232 /dev/shm/sem.xhO5xe
python3 5135 root DEL REG 0,16 18209231 /dev/shm/sem.DXxJQj
python3 5135 root DEL REG 0,16 18209230 /dev/shm/sem.xHio9o
python3 5135 root DEL REG 0,16 18203718 /dev/shm/sem.1pq5ru
python3 5135 root DEL REG 0,16 18203717 /dev/shm/sem.B2iNRc
python3 5135 root DEL REG 0,16 18203716 /dev/shm/sem.xu6vhV
python3 5135 root DEL REG 0,16 18198145 /dev/shm/sem.rBbhHD
python3 5135 root DEL REG 0,16 18198144 /dev/shm/sem.Z4yneZ
python3 5135 root DEL REG 0,16 18198143 /dev/shm/sem.DnUuLk
python3 5135 root 5r FIFO 0,8 0t0 18198146 pipe
python3 5135 root 6r FIFO 0,8 0t0 18203719 pipe
python3 5135 root 7r FIFO 0,8 0t0 18209233 pipe
|
|