Accessing variables in the parent via pointer after clone()

烂漫一生 提交于 2019-12-11 12:19:35

问题


I'm sorry for possibly asking an idiot question, but i'm a bloody beginner in C. Now my problem is, i need to access two variables, declared in main, in a child process and modify them. Sounds very simple, but i have to use clone and after backcasting the variables to my array, they are completely messed up concerining the value.

int main (){
uint64_t N = 10000000;
uint64_t tally = 0;
int status;

void** child_stack = (void**)malloc(65536);
uint64_t** package = (uint64_t**)malloc(sizeof(uint64_t*)*2);
package[0] = &tally;
package[1] = &N;

pid_t cpid;
cpid = clone(child_starter, &child_stack, CLONE_VM , (void*)package);
waitpid(cpid, &status, __WCLONE);
return 0;
}

the child_starter functions looks as follows:

int child_starter(void* package){
printf( "Tally is in the child %" PRIu64 "\n", *((int64_t**)package)[0] );
return 0;
}

since tally is 0, i thought my printf should actually print out 0, but it's more like 140541190785485 changing from run to run..

Hope you can help me :)


回答1:


  • child_stack already is a pointer to valid memory, so do not pass its address, but its value.
  • Stack grows top to bottom, at least on nearly all Linux implementations, so the stack pointer passed needs to be the end of the memory allocated for the stack.


cpid = clone(child_starter, ((char *) child_stack) + 65536, CLONE_VM , package); 

Also in C there is not need to cast to (void*).

Also^2 printf() isn't reentrant so it's use here is error prone.



来源:https://stackoverflow.com/questions/20442072/accessing-variables-in-the-parent-via-pointer-after-clone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!