克隆系统调用的参数存储在堆栈或其他地方?

clone system call's argument stores in stack or somewhere else?

让我们简单地使用 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指定parent和child都允许共享内存,parent中的printf() =] 进程应该打印 10 而不是 50。但它没有发生。为什么?

您忘记使用标志 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).

您需要设置 CLONE_VM 标志。来自 the Linux man page:

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).

clone(stack_func, malloc(1024*1024) + (1024*1024), CLONE_VM | SIGCHLD, &a);