python fork 用法

时间:2022-05-14 04:02:42
import os
import sys ips = ( "192.168.45.%s" % i for i in range(1,255)) for ip in ips:
pid = os.fork()
if pid == 0:
result = os.system("ping -c2 %s" % ip )
if result == 0 :
print "%s:up" % ip
else:
print "%s:down" % ip
sys.exit() 上面的fork方法,容易产生僵尸进程。 #!/usr/bin/env python import os
import sys
import socket
import time host = ''
port = 12345
addr=(host,port)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(addr) s.listen(5) while True:
try:
while True:
result =os.waitpid(-1,os.WNOHANG)
if result[0] == 0:
break
except OSError:
pass
cli, caddr = s.accept()
pid = os.fork() if pid:
cli.close()
else:
s.close() while True:
data = cli.recv(4096)
if not data.strip():
break
cli.send("[%s] %s" % (time.ctime(),data)) cli.close() sys.exit() s.close() 上面的代码,通过 os.waitpid()方法,来销毁僵尸进程