2016-12-17 91 views
1

我有這樣的代碼爲fork從父進程的子過程,我知道:如何從一個子進程派生子進程分別

os.fork()創建先前的Python會話的副本,並打開它並行,os.fork()返回新進程的ID。

我想分別從一個子進程派生一個子進程,但總是從父進程派生出來。如何做到這一點。

import os 

def child(): 
    print('this is child', os.getpgid()) 
    os._exit() 

def parent(): 
    while True: 
     newpid = os.fork() 
     if newpid ==0: 
      child() 

     else: 
      pids = (os.getpid(), newpid) 
      print("parent: %d, child: %d\n", pids) 
      reply = input("q for quit/c for new fork\n") 
      if reply == 'c': 
       continue 
      else: 
       break 

parent() 

以上代碼的輸出:

parent: %d, child: %d 
(1669, 3685) 
q for quit/c for new fork 
c 
parent: %d, child: %d 
(1669, 3686) 
q for quit/c for new fork 
c 
parent: %d, child: %d 
(1669, 3688) 
q for quit/c for new fork 
c 
parent: %d, child: %d 
(1669, 3689) 
q for quit/c for new fork 
q 
+0

'我想從一個孩子fork一個子進程process'那麼,爲什麼不試試呢?現在你的子進程只打印一條消息並退出。 –

回答

0

由於ASTER和chrk。在我讀了答案和一些玩耍之後,我結束了這一點。我用os.wait()

import os 

reply = int(input("Enter no of proc: ")) 
pid = 0 

for i in range(reply): 

    if pid == 0: 
     pid = os.fork() 

if pid != 0: 
    os.wait() 
    print("PID = {}, PPID = {}".format(os.getpid(), os.getppid())) 

併爲num_process = 3結果是:

Enter no of proc: 3 
PID = 49312, PPID = 49311 
PID = 49311, PPID = 49309 
PID = 49309, PPID = 20928 
0

如果從孩子調用fork()再次,返回值將是第一級的兒童和0的孩子非0第二級(孩子的孩子)。

沒有任何的嘗試:

def child(): 
    print('this is child', os.getpid()) 
    if os.fork() == 0: 
     print('this is a grand child', os.getpid()) 
    os._exit(0) 

輸出:

('parent: %d, child: %d\n', (9663, 9664)) 
('this is child', 9664) 
('this is a grand child', 9665) 
+0

我把這個添加到代碼中,但結果是一樣的! – samanv

+0

本地它確實工作。我編輯了我的答案,修復了輸入錯誤並顯示輸出。 'os.fork()'在子中是0,而不是在父進程中。 – AsTeR