让我们简单地使用clone(2)
int stack_func(void *arg)
{
*(int*)arg = 10;
return 0;
}
int main()
{
int a = 50;
clone(stack_func, malloc(1024*1024) + (1024*1024), SIGCHLD, &a);
sleep(2); //Just to be sure
printf("%d\n", a);
return 0;
}
clone()
的 man-page 中指定父进程和子进程都允许共享内存,父进程中的 printf()
应该打印 10不是 50。但它没有发生。为什么?
- 由于 child 的堆栈从顶部的
stack_func
开始,*arg
(不是变量 arg
)将存储在哪里?< - 为什么子进程在修改
arg
的引用时得到一个新副本?
最佳答案
您忘记使用标志 CLONE_VM
:
clone(stack_func, malloc(1024*1024) + (1024*1024), SIGCHLD | CLONE_VM, &a);
CLONE_VM (since Linux 2.0)
If CLONE_VM is set, the calling process and the child process run in the same memory space. In particular, memory writes performed by the calling process or by the child process are also visible in the other process. Moreover, any memory mapping or unmapping performed with mmap(2) or munmap(2) by the child or calling process also affects the other process.
If CLONE_VM is not set, the child process runs in a separate copy of the memory space of the calling process at the time of
clone()
. Memory writes or file mappings/unmappings performed by one of the processes do not affect the other, as with fork(2).
关于克隆系统调用的参数存储在堆栈或其他地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49091887/