【问题标题】:Why clone function return -1 when specifing CLONE_THREAD flag?为什么在指定 CLONE THREAD 标志时克隆函数返回 -1?
【发布时间】:2020-09-07 06:22:57
【问题描述】:

我编写了一个简单的程序来演示线程创建,但是clone 函数返回-1,我不知道我的程序出了什么问题。谢谢。

perror 说Invalid argument

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

static int child_func(void *arg)
{
    sleep(3600);
    return 0;
}

int main(int argc, char **argv)
{
    // Allocate stack for child task.
    const int STACK_SIZE = 65536;
    char *stack = malloc(STACK_SIZE);
    int status;
    if (!stack) {
        perror("malloc");
        exit(1);
    }

    if (clone(child_func, stack + STACK_SIZE, CLONE_THREAD, NULL) == -1) {
        perror("clone");
        exit(1);
    }

    if (wait(&status) == -1) {
        perror("wait");
        exit(1);
    }
    sleep(3600);
    printf("Child exited with status %d. buf = \"%s\"\n", status);
    return 0;
}

【问题讨论】:

  • errno 是什么?你的perror 说了什么?
  • @JosephSible-ReinstateMonica 嗨,我已经更新了描述。 perror 说Invalid argument
  • 你读过manual吗?这个:Since Linux 2.5.35, the flags mask must also include CLONE_SIGHAND if CLONE_THREAD is specified
  • @kaylum 这不起作用。
  • 什么不起作用?手册说您需要这样做,而您的代码没有。所以它可能不是唯一的问题,但它是一个问题。除非你说你使用的是非常旧的内核。

标签: c linux fork


【解决方案1】:

你说你看到了Invalid argument,意思是EINVAL。来自man 2 clone

EINVAL CLONE_THREADflags 掩码中指定,但 CLONE_SIGHAND 未指定。 (从 Linux 2.5.35 开始。)

这正是你正在做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2016-01-11
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多