Accessing variables in the parent via pointer afte

2019-07-31 10:07发布

问题:

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.



标签: c clone