c++中克隆系统调用语句出错

error in clone system call sentence in c++

本文关键字:语句 出错 系统调用 c++      更新时间:2023-10-16

我正试图在内部使用克隆的c++中运行c代码,我遇到了一个无法解决的错误,以前有人在c++中使用过克隆,可以提供帮助。

我的代码:

int variable, fd;
using namespace std ;
int do_something() {
variable = 42;cout << "sana" << endl ;
close(fd);
_exit(0);
}
int main() {
void **child_stack;
char tempch;
variable = 9;
fd = open("test.file", O_RDONLY);
child_stack = (void **) malloc(16384);
printf("The variable was %dn", variable);
clone(do_something, child_stack,CLONE_VM|CLONE_FILES, NULL);
sleep(1);
printf("The variable is now %dn", variable);
if (read(fd, &tempch, 1) < 1) {
  perror("File Read Error");
  exit(1);
}
printf("We could read from the filen");
return 0;
}

我得到了错误:

dell@ubuntu:~$g++n.cpp-o nn.cpp:在函数"int main()"中:n.cpp:40:62:错误:从"int()()"到"int()/usr/include/x86_64-linux-gnu/bits/sched.h:83:12:错误:初始化"int clone(int()(void),void*,int,void*…)"的参数1[-f许可]dell@ubuntu:~$

编译器告诉您,clone的第一个参数应该是int(*)(void*)(指向接受一个void*参数并返回int的函数的指针),您正试图将其传递给int(*)()(指向接受参数且返回int的函数的指示器)。

前者不能隐式转换为后者,因此会出现错误。

要修复它,可以将do_something定义为:

int do_something(void*)
{
    // your code
}

您真的不应该使用clone(2)系统调用。它(有点)像futex(2)一样保留给pthreads的实现。C++11标准实际上要求pthread链接到已编译的应用程序中。

如果您想使用clone(这可能是一个错误),请将自己重新设置为C,并小心避免需要pthread库,即使是间接的;通过您的申请。

如果您坚持使用clone,那么它的child_stack参数应该适当对齐(至少与4K字节的页面对齐),而malloc不能保证这一点。您可以使用mmapposix_memalign

但实际上,不要使用clone(特别是不要使用C++)。使用pthreads。