关于 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?

  • 这意味着 clone 调用失败,您需要检查 errno 以了解原因。您确实需要学习阅读手册页,因为它清楚地写在其中。
  • 除非您有充分的理由,否则我建议使用 POSIX 标准 API,即 fork() 用于进程, pthread_create() 用于线程。在这些标准函数可以做的地方使用 clone() 是不必要地将你的代码限制在 Linux 上。
  • @Someprogrammerdude 抱歉,我错过了关于 errno 的那部分。我才刚刚开始。我使用 strerror(3) 查看原因,我得到了 Operation not permitted。


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

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

运行我的 docker 容器


来源:https://www.codenong.com/44964404/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?