2017-07-07 126 views
0

我有以下程序:的Linux的clone()返回-1作为child_pid

#define _GNU_SOURCE 
#include<sched.h> 
#include<stdio.h> 
#include<stdlib.h> 
#include<sys/wait.h> 
#include<unistd.h> 

static char child_stack[2048]; 

static int child_fn() { 
    printf("Pid: %ld\n", (long) getpid()); 
    return 0; 
} 

int main() { 
    pid_t child_pid = clone(child_fn, child_stack+1024, CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL); 
    printf("clone()= %ld\n", (long) child_pid); 

    waitpid(child_pid, NULL, 0); 
    return 0; 
} 

我得到以下输出

# ./clone                          
clone()= -1 

谁能帮助我理解为什么会这样呢?

注意:我在docker图片下使用ubuntu:latest执行此操作。另外请注意,提示是#而不是$,因此它与正在运行此过程的用户有什么关系,在这种情况下可能是root

+7

运行我的搬运工容器这意味着['clone'(HTTP: //man7.org/linux/man-pages/man2/clone.2.html)call * failed *,你需要检查['errno'](http://man7.org/linux/man-pages/man3 /errno.3.html),看看为什么。你*真的*需要学习阅读手册页,因为它清楚地写在它们中。 –

+1

除非您有很强的理由,否则我建议使用POSIX标准API,即对于进程使用fork(),对于线程使用'pthread_create()'。使用'clone()'这些标准函数可以做的就是不必要地限制你的代码到Linux。 –

+0

@Someprogrammerdude对不起,我错过了关于errno的那一节。我刚刚开始这个。我使用strerror(3)来查看原因,我得到了'不允许的操作'。 –

回答

1

正如在评论中提到的,我使用strerror(3)来找出为什么我得到错误。错误是Operation not permitted。我搜索了一下这件事,在这里找到了解决办法 - clone: operation not permitted

因此,要解决这个问题,我不得不做的是与--privileged标志