Linux system Programming-process

Source: Internet
Author: User
Tags switches

Process in real life

In many scenes, things are done at the same time, for example, when you drive a car with your hands and feet together, you can sing and dance at the same time.

Here is a video of Michael Jackson:

http://v.youku.com/v_show/id_XMzE5NjEzNjA0.html?&sid=40117&from=y1.2-1.999.6

Imagine: If the 2 things to do with singing and dancing are done separately, it's probably not that good.

In the program

The following program, to simulate the "singing and dancing" this thing

  One  fromTime Import Sleep A            -def Sing (): -      forIinchRange3):  thePrint'is singing ...%d'%i) -Sleep1)  -            -def Dance (): +      forIinchRange3):  -Print'are dancing ...%d'%i) +Sleep1)  A            at if__name__=="__main__":  -Sing () -Dance ()

The results of the operation are as follows:

Is singing ... 0 is singing ... 1 is singing ... 2 is dancing ... 0 is dancing ... 1 is dancing ... 2

Attention!!!

Apparently just the procedure did not complete the singing and dancing colleague's request

If you want to achieve "singing and dancing" at the same time, then you need a new method called multi-tasking

Multi-tasking concept

What do you call multitasking? Simply put, the operating system can run multiple tasks at the same time. For example, you use a browser to surf the internet while listening to MP3, while driving word jobs, which is multitasking, at least 3 tasks are running at the same time. There are many tasks quietly running in the background at the same time, but the desktop is not displayed.

Multicore CPUs are now very popular, but even the single-core CPUs of the past can do multitasking. Since the CPU execution code is executed sequentially, how does a single-core CPU perform multi-tasking?

The answer is that the operating system turns each task to perform alternately, Task 1 executes 0.01 seconds, switches to Task 2, Task 2 executes 0.01 seconds, switches to task 3, executes 0.01 seconds ..., and so on. On the surface, each task is executed alternately, but because the CPU is executing too fast, we feel that all the tasks are executing at the same time.

True parallel multitasking can only be done on multicore CPUs, but because the number of tasks is much larger than the number of cores in the CPU, the operating system automatically shifts many tasks to each core.

Why do single-core CPUs perform multiple tasks?

    • The method of time slice theory
    • Priority scheduling

Parallel and concurrency

Concurrency: Looks like it's been executed

Parallel: true execution together

creation of the process-forkProcess vs Program

Code that has been written is called a program when it is not running.

Code that is running is called a process

Process, in addition to containing code, there is a need to run the environment, etc., so there is a difference with the program

Fork ()

Python's OS module encapsulates common system calls, including fork, which makes it easy to create child processes in a Python program:

        pid =       if0       print (' haha 0'Else print ( ' haha 1 ')         

The results of the operation are as follows:

haha 1 haha 0

There is one more example:

11ImportOS12Import TimeRET =os.fork ()15ifret==0:16 whileTrue:17Print('------------1-------------')                           Time.sleep (1) 19Else:     20 whileTrue:21stPrint('------------2-------------') Time.sleep (1)

The results of the operation are as follows:

------------2-------------------------1-------------------------1-------------------------2------------------- ------1-------------------------2-------------------------2-------------------------1-------------... 

Equivalent to a program running to Os.fork (), a new process is generated, RET is used to accept two process return values, the old process executes the most of the following statement, and the new process executes the above statement, because the new process returns a value of 0. The previous process is called the parent process, and the newly created process is called the child process.

Because the parent process and child processes are to be distinguished, the return value of the operating system to the parent process is greater than 0, and the return value of the child process equals 0.

The operating system scheduling algorithm determines the order in which the parent and child processes run.

Description

    • The program executes to Os.fork (), the operating system creates a new process (child process), and then copies all the information of the parent process into the child process
    • Then both the parent and child processes get a return value from the fork () function, which must be 0 in the child process, and the parent process is the child process ID number

In the Unix/linux operating system, a fork () function is provided, which is very special.

A normal function call, called once, is returned once, but the fork () is called once and returned two times because the operating system automatically copies the current process (called the parent process), which is then returned within the parent and child processes, respectively.

The child process always returns 0, and the parent process returns the ID number of the child process.

The reason for this is that a parent process can fork out a lot of child processes, so the parent process has to note the ID of each child process, and the child process only needs to call Getppid () to get the ID of the parent process.

return value of fork
Importof   ret =print(ret)  

Operation Result:

26517   #代表着父进程 0 #代表子进程
Getpid (), Getppid ()

Getpid () Gets the value of the current process, getppid () Gets the value of the parent process for the current process.

  AImport OS -PID =os.fork () -    the ifpid<0:  -Print'The fork call failed.')  -Elif pid==0:  -Print'I am a child process (%s), my parent process is (%s)'%(Os.getpid (), Os.getppid ())) + Else:  -Print'I am the parent process (%s), my child process is (%s)'%(Os.getppid (), Os.getpid ())) +    APrint'code that both parent and child processes can execute <F8>')

The results of the operation are as follows:

I am the parent process (2774), my child process is (25874) The code that the parent-child process can execute <F8> I am a child process (25875), My parent process is code that (25874) A parent-child process can execute <F8>

A second example:

Import OS
PID = Os.fork ()
Print (PID)
14
If pid>0:
Print (' Parent process:%d '%os.getpid ())
+ Else:
Print (' Sub-process:%d-%d '% (Os.getpid (), Os.getppid ()))

Operation Result:

26685 #pid的返回值, the operating system in order to manage the value to it, the return value of the parent class is the ID number of the child process parent process:26684 #26684是父进程ID号0 Child process:26685-26684 # 26685 is the child process ID number, and the parent process of the child process is 26684

Multi-process Modify global variables
  OneImport OS AImport Time /c3> -              -num =0      the              -PID =os.fork () -              - ifpid==0:   +num+=1   -Print'haha 1------num=%d'%num) + Else:        ATime.sleep (2)  atnum+=1   -Print'haha 2------num=%d'%num)

The results of the operation are as follows:

Haha 1------num=1 haha 2------num=1

Description

    • In a multi-process, the data in each process (including global variables) has one copy, without impact, and no data sharing between processes and processes
Multiple fork Problems

If there is a program that has 2 fork function calls, will there be 3 processes?

  OneImport OS AImport Time -    -PID =os.fork () the ifpid==0:  -Print'haha 1')  - Else:  -Print'haha 2') #一共运行了2次 +    -PID =os.fork () + ifpid==0:  APrint'haha 3')  at Else:  -Print'haha 4') #一共运行了4次 -    -Time.sleep (1)

The results of the operation are as follows:

[Email protected]:~/codes/liunx system programming/- multiple fork calls. py haha 2 haha 1 haha 4 haha 4 haha 3 haha 3

Description

Order of execution of parent-child processes

The sequence of parent process and sub-process execution is not regular, it depends entirely on the operation system scheduling algorithm

11ImportOS12Import TimeRET =os.fork ()14 15ifret==0:16Print('Child Process') Time.sleep (1) 18Print('Child process over') #end = ""19Else: 20Print('Parent Process')

The results of the operation are as follows:

Python3 04- The run order of the parent-child process. PY Parental process Sub-process [email protected]:~/CODES/LIUNX system Programming/01-Process $ sub-process over

Because the parent process is over, it means that the terminal is ready to start prompting, so when the parent process is finished, the terminal will come out immediately.

Advantages of multi-tasking

Increase the operational efficiency of the program, such as crawlers

Multiprocessing

UNIX and Linux are undoubtedly the right choice if you are going to write a multi-process service program. Because Windows does not have a fork call, isn't it possible to write multi-process programs in Python on Windows?

Because Python is cross-platform, nature should also provide a cross-platform multi-process support, the Multiprocess module is a cross-platform version of the multi-process module.

The Multiprocessessing module provides a process class to represent a processing object, and the following example demonstrates starting a child process and waiting for it to end:

Linux system Programming-process

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.