2016-08-01 47 views
0

我是一個嘗試使用fork多叉進程的python新手。我想要做的是在少數主機上運行命令。我可以使用下面的代碼,但是我也想停止執行,如果有任何孩子無法運行命令或命令本身失敗。os.fork退出腳本如果孩子無法運行命令

def runCommand(host,comp): 
    if os.system("ssh "+host+" 'somecommand'") != 0: 
      print "somecommand failed on "+host+" for "+comp 
      sys.exit(-1) 

def runMulti(): 
    children = [] 
    for comp,host in conHosts.iteritems(): 
      pid = os.fork() 
      if pid: 
        children.append(pid) 
      else: 
        sleep(5) 
        runCommand(host,comp) 
        os._exit(0) 

    for i, child in enumerate(children): 
      os.waitpid(child, 0) 
+0

如果代碼工作,那麼爲什麼要求存在我創建了一個臨時文件,? –

+0

這可能會更好的代碼review.se –

+0

您的縮進是奇怪的 –

回答

0

我已經通過使用ThreadPool實現了這一點。

pool = ThreadPool(len(hosts)) 
    try: 
      pool.map(runMulti(), 'True') 
      pool.close() 
      pool.join() 
    except: 
      os.system('touch /tmp/failed') 
      commands.getoutput("killall -q ssh") 
      os.kill(os.getpid(),9) 

當池中的線程不同status.Thank大家:)

0

你可以只檢查waitpid返回值,看看子進程具有不同的狀態,從0退出:

had_error = any(os.waitpid(child, 0)[1] for child in children) 
if had_error: 
    sys.exit(1) 

注:因爲要檢查的返回值os.fork列表children將在子進程中爲空,因此any將始終返回False,即只有主進程最終會調用sys.exit

0

os.fork()在子進程中返回0。所以,你可以這樣做:

if not os.fork(): 
    # we now know we're the child process 
    execute_the_work() 
    if failed: 
     sys.exit() 

sys.exit()是退出Python程序的Python的方式。不要忘記import sys

由於您似乎是一名初學者,請用條件替換failed以判斷任務是否失敗。

+0

請注意['os._exit']的文檔(https://docs.python.org/3.5/library/os .html#os._exit)state:「**注意**標準的退出方式是'sys.exit(n)'。**'_exit()'通常應該只在子進程中使用'fork ()'。**「換句話說,OP的代碼非常好。 – Bakuriu

相關問題