clone在c ++中导致分段错误

时间:2012-09-15 13:14:51

标签: c++ segmentation-fault clone

克隆导致分段错误

代码:

#define STACKSIZE 16384
int variable ;
using namespace std ;
int do_something(void *) {
    variable = 42;
return 0 ;
}

int main() {
void *child_stack;
variable = 9;
child_stack = (void *) malloc(STACKSIZE);
printf("The variable was %d\n", variable);
clone(do_something, child_stack,CLONE_VM|CLONE_FILES,NULL );
sleep(1);
printf("The variable is now %d\n", variable);
free(child_stack);
return 0;
}

1 个答案:

答案 0 :(得分:3)

阅读man page for clone

  

在运行Linux的所有处理器(HP PA处理器除外)上堆栈向下增长,因此child_stack通常指向为子堆栈设置的内存空间的最顶层地址。

所以我会尝试这样的事情:

char* child_stack = (char*) malloc(STACKSIZE);
child_stack += STACKSIZE - 1;  // set it to the topmost address
                               // of allocated space

clone(do_something, (void*) child_stack, CLONE_VM|CLONE_FILES, NULL);