haolee
haolee

Reputation: 937

Why clone function return -1 when specifing CLONE_THREAD flag?

I write a simple program to demonstrate the thread creation, but the clone function return -1 and I don't know what's wrong with my program. Thanks.

The perror says 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;
}

Upvotes: 0

Views: 229

Answers (1)

You said you saw Invalid argument, which means EINVAL. From man 2 clone:

EINVAL CLONE_THREAD was specified in the flags mask, but CLONE_SIGHAND was not. (Since Linux 2.5.35.)

And that's exactly what you're doing.

Upvotes: 1

Related Questions