Programming Python - 2. System Tools -2.5 Parallel System Tools
Forking is based on the notion of copying programs: when a program calls the fork routine, the
operating system makes a new copy of that program and its process in memory and
starts running that copy in parallel with the original. Some systems don’t really copy
the original program (it’s an expensive operation), but the new copy works as if it were
a literal copy.
all forked processes run independently and in parallel under the operating system’s control, and
children may continue to run after their parent exits.
os.fork built-in function. Because this function
generates a copy of the calling program, it returns a different value in each copy: zero
in the child process and the process ID of the new child in the parent
import os def child(): print("hello from child", os.getpid()) os.exit(0) def parent(): while True: newpid=os.fork() if newpid==0: child() else: print("hello from parent",os.getpid(), newid) if input()=='q': break parent()
*fork cannot work well in typical win; but can work under cygwin
浙公网安备 33010602011771号