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

标签 c linux memory-management stack clone

让我们简单地使用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/

相关文章:

linux - 如何从带有参数的变量执行 Bash 命令

c - Windows x64 上的 MySQL C Connector 与 GCC 链接错误

c - libxml2 的巨大内存泄漏

java - 无法从 Java 执行 Linux 命令

c - 实现文件描述符

c - 访问带下标的 long long int 指针

c - C 位运算的行为

c - 基于函数的 CPE,如何计算下限?

.net - 计数 "new"和 "delete"字节

iphone - Objective-C/iPhone 内存管理静态变量