Python Multi-process--fork () __python

Source: Internet
Author: User
1, Linux under the fork ()
Usage: Import OS
Help (Os.fork):
Functions built into Linux modules fork:
Fork (): derives a child process.
Child process returns 0
PID for the parent process to return the child process
Cases:
  Import OS
# Note that the fork function, only run on Unix/linux/mac, Windows can not be
  pid = os.fork ()
  If pid = 0:
      print (' haha 1 ')
   else:
      print (' Haha 2 ')

results:
        haha 2
        haha 1

Description
When a program executes to Os.fork (), the operating system creates a new process (subprocess), and then copies all the information from the parent process into the child process
Both the parent process and the subprocess then get a return value from the fork () function, which must be 0 in the child process, and the ID number of the child process in the parent process.

2, Os.getpid (), Os.getppid ()
Os.getpid (): Returns the PID of the current process
Os.getppid (): Returns the PID of the parent process of the current process

3, multiple fork problems

Cases:

#coding =utf-8
import os
import time

# Note that the fork function, run only on Unix/linux/mac, Windows cannot be
pid = os.fork ()
If PID = = 0:
    print (' haha 1 ')
else:
    print (' Haha 2 ')

pid = os.fork ()
If pid = 0:
    print (' haha 3 ')
else:
    print (' haha 4 ')

Time.sleep (1)

Results:

Description




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.