c - fork() 是否为子进程创建了父进程创建的所有变量和对象的重复实例?

标签 c multithreading fork

假设我有一个主进程在运行,并且在它的执行过程中它初始化了一些指针并创建了一些预定义结构的实例。

现在,如果我 fork 这个主进程,是否为指针分配了单独的内存?并且是为这个新进程创建的先前存在的变量、数据结构的重复实例吗?

作为我的要求的一个例子,考虑 -

struct CKT
{
  ...
}

main()
{
   ...Some computations with the structure and other pointers.....
   pid_t pid = fork();
   if(pid == 0) //child
   {
       ..some more computations with the structure...but I need a 
       ..separate instance of it with all the pointers in it as well..
   }
   else if(pid > 0) // parent
   {
       ..working with the original instance of the structure..
   }
   // merging the child process with the parent...
   // after reading the data of the child processes structure's data... 
   // and considering a few cases...
}

谁能解释我如何实现这一目标?

最佳答案

指针和内存内容都将为 fork 子级复制。

所有类型的数据指针、内存、变量都将在一个单独的内存中为使用 fork 创建的子进程复制。并且您无法直接从进程子进程更改指针或内存内容。

但是您可以使用内存共享从子进程更改父进程的变量

请参阅此链接以了解如何操作:How to share memory between process fork()?

关于c - fork() 是否为子进程创建了父进程创建的所有变量和对象的重复实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13286931/

相关文章:

c - 出现错误 "In function ' _start' : (. text+0x20): 对 `main' 的 undefined reference “无法使用类似问题的答案来解决

多个分隔符的代码核算不起作用

C 写入文件的可重复选择问题

asp.net - 在 ASP.Net Web 应用程序中运行后台任务并获取反馈的最佳方式?

使用 fork() 和 exec() 在终端中创建新命令

C Pthreads - 父/子

c++ - C++ DLL def 文件中的重载函数

java - 简单的一种方式挂起线程

c++ - 使用原子而不是 CriticalSection?

open-source - BSD 许可证 : How to manage attribution and project name in a fork