What's the use of fork?

Source: Internet
Author: User

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main ()
{
pid_t pid1;
pid_t Pid2;
pid1 = fork ();
Pid2 = fork ();
printf ("pid1:%d, pid2:%d\n", Pid1, Pid2);
}

Output:
pid1:3411, pid2:3412//parent process returns two times
pid1:0, pid2:3413//Sub-process 1 return two times
pid1:3411, pid2:0//Sub-process 2 return once
pid1:0, pid2:0//Sun Process 3 to return once

1) The fork function is always "called once, returns two times", is called once in the parent process, and is returned once in the parent and child processes. The return value of fork in the child process is 0, and the return value in the parent process is the ID of the child process.
2) The child process copies the current state of the parent process when it is created (the same as the PCB information, and the same for the user state Code and data).
3) The result of the program operation is basically the parent-child process alternately printing, but this is not certain, depending on the operation of other processes in the system and the kernel scheduling algorithm.

The fork in Linux is implemented with clone. The process of fork and the parent process is not the same as the PID, others are the same (basically), that is, the parent process copies a copy. Note, however, that the copy action does not occur until the child process is actually executed because Linux considers clone to be exec. EXEC copies the code that the process actually executes to the address space. Because a simple fork is a copy of a parent process, not very useful.

What's the use of fork?

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.