About fork system call and global variables

前端 未结 5 1508
遥遥无期
遥遥无期 2021-01-15 04:57

I have this program in C++ that forks two new processes:

#include 
#include 
#include 
#include 

        
相关标签:
5条回答
  • 2021-01-15 05:29

    This is called "virtual address". Each process has its own address space, and each address means something different, depending on the process. fork() creates a copy, instead of sharing data (technically, they may get shared copy-on-write, but this is has the same effect as upfront copying would). IOW, the variable "shared" is not shared between processes.

    0 讨论(0)
  • 2021-01-15 05:50

    yes what you have thought is right but in order to save some memory, internally the pages are shared between the parent and the child till the child executes exec system call or modifies any of the variables or the data structures.since many pages are shared between parent and child.....if the page is modified by child,then that page will copied into separate memory area and will be assigned to the child.if it is modified by parent,then that page will be copied to separate memory area and assigned to the parent

    0 讨论(0)
  • 2021-01-15 05:51

    Does this apply to pthread_mutex objects also. Say I have mutex in the parent that gets locked and unlocked in a particular function. Now the parent creates a child process. Both parent and child can call this function simultaneously (Parent not really blocked till child exits as parent is a multi-threaded program, the thread that spawns child is only one blocked). So is the mutex object state - shared between the 2 processes? If in parent, mutex was locked then child was created child gets to run first child sees the mutex in locked state as it has just inherited the mutex object as it is from parent now child unlocks mutex How is the state of this mutex in parent now - still locked (because parent never unlocked) or Unlocked because child has unlocked it.

    Is it ok to call such a function that locks/unlocks global mutexes from parent and child?

    0 讨论(0)
  • 2021-01-15 05:52

    Pointers on modern systems doesn't correspond to actual hardware memory addresses. Rather the addresses maps to a virtual space managed by the operating system. Therefore the pointer addresses for two different processes can appear to be the same when they in reality are not.

    0 讨论(0)
  • 2021-01-15 05:56

    The OS is using virtual memory and similar techniques to ensure that each process sees different memory cells (virtual or read) at the same addresses; only memory that's explicitly shared (e.g. via shm) is shared, all memory by default is separate among separate processes.

    0 讨论(0)
提交回复
热议问题