Many processes in Python are basically the same as C under Linux.
Basic use of fork
Let's look at the simplest example:
#Coding:utf-8ImportOSdefmy_fork (): PID=os.fork ()ifPID = =0:Print 'This is child, PID =%d, parent id =%d'%(Os.getpid (), Os.getppid ())elifPID >0:Print 'This is the parent, PID =%d, child id =%d'%(Os.getpid (), PID) os.waitpid (PID, 0)#wait for the child process to endif __name__=='__main__': My_fork ()
This example demonstrates the basic use of fork, and finally we use Waitpid to reclaim the child process.
If you do not know the specific child process number, you can use the wait function.
Use of piping pipe
The code is as follows:
#Coding:utf-8ImportOS fromTimeImportSleepdefmy_fork (): R, W=os.pipe () PID=os.fork ()ifPID = =0:os.close (R)#Close the Read endW = Os.fdopen (W,"W") forIinchRange (10): W.write ('%s\n'% (str (i+1)))#finally add \ nW.flush ()#here remember refreshSleep (0.5) W.close ()elifPID >0:os.close (W)#Close the Write endR = Os.fdopen (R,"R") whileTrue:data= R.readline ()#do not use read if notData:Print 'Close.' Break; Print 'Received:%s'%(data) os.waitpid (PID, 0)#wait for the child process to endif __name__=='__main__': My_fork ()
In a child process, a number is sent 10 times in a row.
Here are a few noteworthy points to note:
Add \ n Symbol when write
Use the ReadLine function when receiving
Flush one buffer at a time after each data is sent
Using signals to process zombie processes
Signal processing functions, such as the simplest interrupt signal, can also be used in Python:
#Coding:utf-8ImportOSImportSignal fromTimeImportSleepdefHandler (A, b):Print 'Ctrl + C'if __name__=='__main__': signal.signal (signal. SIGINT, Handler) whileTrue:Pass
Each time you press CTRL + C, the function is triggered once.
The code is as follows:
#Coding:utf-8ImportOSImportSignal fromTimeImportSleepdefHandler (A, B): (PID, status)=os.wait ()Print 'Child %d Finish, status =%d'%(PID, status)defmy_fork (): PID=os.fork ()ifPID = =0:Print 'This is child, PID =%d, parent id =%d'%(Os.getpid (), Os.getppid ())elifPID >0:Print 'This is the parent, PID =%d, child id =%d'%(Os.getpid (), PID) whileTrue:Passif __name__=='__main__': signal.signal (signal. SIGCHLD, Handler) my_fork ()
Whenever a child process dies, the SIGCHLD signal is triggered and the wait function is called in the handler function. This is simpler than Linux, and does not have to be recycled using while loops.
The next section uses Python to write a multi-process concurrent server.
Finish.
Python Learning Notes (iv) use of multiple processes