关于 c:linux clone() 返回 -1 作为 child_pid

linux clone() returning -1 as child_pid

我有以下程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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\
"
, (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\
"
, (long) child_pid);

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

我得到以下输出

1
2
# ./clone                                                                                                      
clone()= -1

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

Note: I'm running this under a docker image with ubuntu:latest. Also notice that the prompt is # instead of $, so does it have anything to do with the user who's running this process, probably root in this case?


正如评论中提到的,我使用 strerror(3) 来找出我收到错误的原因。错误是 Operation not permitted。我对其进行了一些搜索,并在此处找到了解决方案-克隆:不允许操作

所以要修复它,我所要做的就是使用 --privileged 标志

运行我的 docker 容器