(1)
import subprocess
import threading
def ping(host):
result = subprocess.call(
‘ping -c2 %s &> /dev/null’ % host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print(‘%s’ % host)
# else:
# print(‘%s:down’ % host)
if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips: # 主线程用于产生工作线程
t = threading.Thread(target=ping, args=(ip,))
t.start() # 将会执行ping(ip),执行完就停止了,不会有僵尸进程
# 主线程不会等待工作线程结束,直接进入下次循环
(2)
import threading
import subprocess
class Ping:
# def init(self, host):
# self.host = host
def __call__(self, host):
result = subprocess.call(
'ping -c2 %s &> /dev/null' % host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print('%s:up' % host)
else:
print('%s:down' % host)
if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
t = threading.Thread(target=Ping(), args=(ip,))
t.start() # Ping(ip)() <==> target()
(3)
import threading
import subprocess
class Ping:
def init(self, host):
self.host = host
def __call__(self):
result = subprocess.call(
'ping -c2 %s &> /dev/null' % self.host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print('%s:up' % self.host)
else:
print('%s:down' % self.host)
if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
t = threading.Thread(target=Ping(ip))
t.start() # Ping(ip)() <==> target()
(4)
import subprocess
import os
def ping(host):
result = subprocess.call(
‘ping -c2 %s &> /dev/null’ % host,
shell=True
)
if result == 0: # result的值就是ping命令的退出码,即$?
print(‘%s:up’ % host)
else:
print(‘%s:down’ % host)
if name == ‘main‘:
ips = [‘172.40.58.%s’ % i for i in range(1, 255)]
for ip in ips:
pid = os.fork() # 父进程负责生成子进程
if not pid: # 子进程负责ping
ping(ip)
exit() # 子进程ping完一个地址后结束,不要再循环