使用clone():分段错误
我想使用克隆来记录程序的当前状态。 它有很多循环,我想跟踪该过程,而不是在每个循环迭代中打印状态。
这就是我创建这个概念验证的原因:
#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;
}
当我在没有 gdb 的情况下运行它时,它会因 clone() 处的分段错误而崩溃,但如果我使用 gdb,它就可以正常工作。为什么?
你认为这是一个好的做法还是我迟早会遇到麻烦? 有没有更好的方法来实现这一目标?
干杯,
曼努埃尔
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
clone
的堆栈参数是一个简单的void*
。此外,在大多数体系结构上,堆栈都会向下增长,因此堆栈指针应指向已分配内存的末尾。无论如何,您不应该直接使用
clone
,除非您确实需要避免对外部库的任何依赖。请改用 pthreads 库。它提供了更简单(也更安全)的 API。The stack argument to
clone
is a simplevoid*
. 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.在英特尔处理器上,
child_stack
参数应指向堆栈顶部,而不是底部。不管怎样,我认为使用
clone
不是一个好主意。根据架构的不同,大约有三种调用clone
的方法,但这些方法的文档都很少。我建议使用 pthreads 库(或者,因为我们使用 C++,所以使用 Boost.Threads)。On intel processors, the
child_stack
argument should point to the top of the stack, not to the bottom.Anyway, I think using
clone
is not a good idea. There are about three ways of callingclone
, depending on architercture, all poorly documented. I'd suggest using the pthreads library (or, since we are in C++, Boost.Threads).