Python中os.fork()产生子进程

3/8/2017来源:ASP.NET技巧人气:1919

例1

import os PRint 'Process (%s) start...' %os.getpid() pid = os.fork() if pid==0: print 'I am child (%s) and my father is %s.'%(os.getpid(),os.getppid()) else: print 'I (%s) just created a child process (%s).' %(os.getpid(),pid)

加载os模块后,首先os.fork()函数生成一个子进程,返回值pid有两个,一个为0, 用以表示在子进程当中,一个是大于0的整数,表示在父进程,这个常数正是子进程的pid. if pid == 0,在子进程当中os.getpid()是子进程的pid,os.getppid()是父进程pid if pid >0 ,在父进程当中,os.getpid()是父进程的pid,os.fork()返回的就是子进程的pid

例2

import os def child(): print 'A new child:', os.getpid() print 'Parent id is:', os.getppid() os._exit(0) def parent(): while True: newpid=os.fork() print newpid if newpid==0: child() else: pids=(os.getpid(),newpid) print "parent:%d,child:%d"%pids print "parent parent:",os.getppid() if raw_input()=='q': break parent()