What is the purpose of fork()?

前端 未结 15 1217
悲哀的现实
悲哀的现实 2020-12-12 11:11

In many programs and man pages of Linux, I have seen code using fork(). Why do we need to use fork() and what is its purpose?

相关标签:
15条回答
  • 2020-12-12 11:25

    fork() will create a new child process identical to the parent. So everything you run in the code after that will be run by both processes — very useful if you have for instance a server, and you want to handle multiple requests.

    0 讨论(0)
  • 2020-12-12 11:25

    System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork():

    If fork() returns a negative value, the creation of a child process was unsuccessful. fork() returns a zero to the newly created child process. fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to retrieve the process ID assigned to this process. Therefore, after the system call to fork(), a simple test can tell which process is the child. Please note that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.

    Let us understand it with an example to make the above points clear. This example does not distinguish parent and the child processes.

    #include  <stdio.h>
    #include  <string.h>
    #include  <sys/types.h>
    
    #define   MAX_COUNT  200
    #define   BUF_SIZE   100
    
    void  main(void)
    {
         pid_t  pid;
         int    i;
         char   buf[BUF_SIZE];
    
         fork();
         pid = getpid();
         for (i = 1; i <= MAX_COUNT; i++) {
              sprintf(buf, "This line is from pid %d, value = %d\n", pid, i);
              write(1, buf, strlen(buf));
         } 
    }
    

    Suppose the above program executes up to the point of the call to fork().

    If the call to fork() is executed successfully, Unix will make two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call. In this case, both processes will start their execution at the assignment

    pid = .....;
    

    Both processes start their execution right after the system call fork(). Since both processes have identical but separate address spaces, those variables initialized before the fork() call have the same values in both address spaces. Since every process has its own address space, any modifications will be independent of the others. In other words, if the parent changes the value of its variable, the modification will only affect the variable in the parent process's address space. Other address spaces created by fork() calls will not be affected even though they have identical variable names.

    What is the reason of using write rather than printf? It is because printf() is "buffered," meaning printf() will group the output of a process together. While buffering the output for the parent process, the child may also use printf to print out some information, which will also be buffered. As a result, since the output will not be send to screen immediately, you may not get the right order of the expected result. Worse, the output from the two processes may be mixed in strange ways. To overcome this problem, you may consider to use the "unbuffered" write.

    If you run this program, you might see the following on the screen:

    ................
    This line is from pid 3456, value 13
    This line is from pid 3456, value 14
         ................
    This line is from pid 3456, value 20
    This line is from pid 4617, value 100
    This line is from pid 4617, value 101
         ................
    This line is from pid 3456, value 21
    This line is from pid 3456, value 22
         ................
    

    Process ID 3456 may be the one assigned to the parent or the child. Due to the fact that these processes are run concurrently, their output lines are intermixed in a rather unpredictable way. Moreover, the order of these lines are determined by the CPU scheduler. Hence, if you run this program again, you may get a totally different result.

    0 讨论(0)
  • 2020-12-12 11:25

    Fork() system call use to create a child process. It is exact duplicate of parent process. Fork copies stack section, heap section, data section, environment variable, command line arguments from parent.

    refer: http://man7.org/linux/man-pages/man2/fork.2.html

    0 讨论(0)
  • 2020-12-12 11:28

    First one needs to understand what is fork () system call. Let me explain

    1. fork() system call creates the exact duplicate of parent process, It makes the duplicate of parent stack, heap, initialized data, uninitialized data and share the code in read-only mode with parent process.

    2. Fork system call copies the memory on the copy-on-write basis, means child makes in virtual memory page when there is requirement of copying.

    Now Purpose of fork():

    1. Fork() can be used at the place where there is division of work like a server has to handle multiple clients, So parent has to accept the connection on regular basis, So server does fork for each client to perform read-write.
    0 讨论(0)
  • 2020-12-12 11:32

    Fork creates new processes. Without fork you would have a unix system that could only run init.

    0 讨论(0)
  • 2020-12-12 11:33

    Fork() is used to create new processes as every body has written.

    Here is my code that creates processes in the form of binary tree.......It will ask to scan the number of levels upto which you want to create processes in binary tree

    #include<unistd.h> 
    #include<fcntl.h> 
    #include<stdlib.h>   
    int main() 
    {
    int t1,t2,p,i,n,ab;
    p=getpid();                
    printf("enter the number of levels\n");fflush(stdout);
    scanf("%d",&n);                
    printf("root %d\n",p);fflush(stdout);
    for(i=1;i<n;i++)    
    {        
        t1=fork();
    
        if(t1!=0)
            t2=fork();        
        if(t1!=0 && t2!=0)        
            break;            
        printf("child pid %d   parent pid %d\n",getpid(),getppid());fflush(stdout);
    }   
        waitpid(t1,&ab,0);
        waitpid(t2,&ab,0);
    return 0;
    }
    

    OUTPUT

      enter the number of levels
      3
      root 20665
      child pid 20670   parent pid 20665
      child pid 20669   parent pid 20665
      child pid 20672   parent pid 20670
      child pid 20671   parent pid 20670
      child pid 20674   parent pid 20669
      child pid 20673   parent pid 20669
    
    0 讨论(0)
提交回复
热议问题