Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux?

后端 未结 4 722
故里飘歌
故里飘歌 2020-12-05 06:39

I have a program with a parent and a child process. Before the fork(), the parent process called malloc() and filled in an array with some data. After the fork(), the chil

4条回答
  •  Happy的楠姐
    2020-12-05 07:25

    The short answer is 'dirty on write' - the longer answer is .. a lot longer.

    But for all intends and purposes - the working model which at C level is safe to assume is that just after the fork() the two processes are absolutely identical -- i.e. the child gets a 100% exact copy -- (but for a wee bit around the return value of fork()) - and then start to diverge as each side modifies its memory, stack and heaps.

    So your conclusion is slightly off - child starts off with the same data as parent copied into its own space - then modifies it - and see s it as modified - while the parent continues with its own copy.

    In reality things are bit more complex - as it tries to avoid a complete copy by doing something dirty; avoiding to copy until it has to.

    Dw.

提交回复
热议问题