c ++中克隆系统调用句子中的错误

时间:2012-09-15 12:14:09

标签: c++ linux clone

我试图在c ++中运行c代码,里面使用了clone,我得到了一个我无法解决的错误,之前有人在c ++中使用了clone,并且可以提供帮助。

我的代码:

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 %d\n", variable);

clone(do_something, child_stack,CLONE_VM|CLONE_FILES, NULL);
sleep(1);

printf("The variable is now %d\n", variable);
if (read(fd, &tempch, 1) < 1) {
  perror("File Read Error");
  exit(1);
}
printf("We could read from the file\n");
return 0;
}

我得到了错误:

dell @ ubuntu:〜$ g ++ n.cpp -o n n.cpp:在函数'int main()'中: n.cpp:40:62:错误:从'int()()'转换为'int()(void *)'无效转换[-fpermissive] /usr/include/x86_64-linux-gnu/bits/sched.h:83:12:错误:初始化'int clone(int()(void )的参数1,void *,int, void *,...)'[-fpermissive] dell @ ubuntu:〜$

2 个答案:

答案 0 :(得分:5)

编译器告诉你clone的第一个参数应该是int(*)(void*)(一个指向函数的指针,它带有一个void*参数并返回int)并且你'重新尝试传递它int(*)()(指向函数的指针 no 参数并返回int)。

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

要解决此问题,您可以将do_something定义为:

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

答案 1 :(得分:1)

你真的不应该使用clone(2)系统调用。对于pthreads的实现,它(类似于)保留类似futex(2)。而C ++ 11标准实际上要求将pthread链接到已编译的应用程序中。

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

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

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

相关问题