Search code examples
c++segmentation-faultclone

using clone(): segmentation fault


I want to use clone to log the current status of my program. It has a lot of loops and I want to keep track of the process without printing the status in each loop iteration.

That's why I created this proof-of-concept:

#include <iostream>
#include <cstdlib>

unsigned int i;

int log(void*) {
  std::cout << "LOGGING START" << std::endl;
  while(true) {
    sleep(1);
    std::cout << i << std::endl;
  }
}

int main()  {
  void **child_stack = (void**)malloc(16384);
  i = 0;

  std::clog << "calling clone" << std::endl;
  clone(log, child_stack, CLONE_VM | CLONE_FILES, NULL);
  std::clog << "done" << std::endl;

  while(true) {
    ++i;
  }

  return 0;
}

When I run it without gdb it crashes with a segmentation fault at clone() but it works fine if I use gdb. Why?

Do you think this is a good practice or will I run into troubles sooner or later? And is there a better method to achieve this?

Cheers,

Manuel


Solution

  • The stack argument to clone is a simple void*. Also, the stack grows down on most architectures, so the stack pointer should point to the end of the allocated memory.

    In any case, you shouldn't use clone directly unless you really need to avoid any dependencies on external libraries. Use the pthreads library instead. It provides a much easier (and safer) API.