fork() system call and memory space of the process

前端 未结 6 412
一个人的身影
一个人的身影 2020-12-24 08:54

I quote \"when a process creates a new process using fork() call, Only the shared memory segments are shared between the parent process and the newly forked child process. C

6条回答
  •  执念已碎
    2020-12-24 09:53

    Yes address in both the case is same. But if you assign different value for x in child process and parent process and then also prints the value of x along with address of x, You will get your answer.

    #include  
    #include  
    #include 
    #include 
    #define   MAX_COUNT  200
    
    void  ChildProcess(void);                /* child process prototype  */
    void  ParentProcess(void);               /* parent process prototype */
    
    void  main(void)
    {
        pid_t  pid;
        int * x = (int *)malloc(10);
    
        pid = fork();
        if (pid == 0) {
                *x = 100;
                ChildProcess();
        }
        else {
                *x = 200;
                ParentProcess();
        }
        printf("the address is %p and value is %d\n", x, *x);
    }
    
    void  ChildProcess(void)
    {
        printf("   *** Child process  ***\n");
    }
    
    void  ParentProcess(void)
    {
        printf("*** Parent*****\n");
    }
    

    Output of this will be:

    *** Parent*****
    the address is 0xf70260 and value is 200
    *** Child process  ***
    the address is 0xf70260 and value is 100
    

    Now, You can see that value is different but address is same. So The address space for both the process is different. These addresses are not actual address but logical address so these could be same for different processes.

提交回复
热议问题