假设我有一个主进程在运行,并且在它的执行过程中它初始化了一些指针并创建了一些预定义结构的实例。
现在,如果我 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/