From e618f5a058d37cf612851dc04c1e321292efde02 Mon Sep 17 00:00:00 2001 From: leonnicolas Date: Mon, 8 Jun 2020 13:32:12 +0200 Subject: [PATCH] initial commit --- Makefile | 3 +++ README.md | 11 +++++++++++ main.c | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 Makefile create mode 100644 README.md create mode 100644 main.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3a0c405 --- /dev/null +++ b/Makefile @@ -0,0 +1,3 @@ +main: main.c + gcc -Wall -Wextra -pedantic -o main main.c -pthread + diff --git a/README.md b/README.md new file mode 100644 index 0000000..7d3049f --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# Clone Thread Example +This C program uses clone() to create a new thread. It illustrates, that the new thread shares the same data and heap segment. The main process creates a new thread with clone. clone() will execute a function that prints a buffer to stdout and then waits 2 seconds and does it again. In the meantime, the main thread changes the content of the buffer. That the child thread prints different things shows that they are not seperate processes. + +# Compile +``` +make +``` +# Run +```bash +./main +``` diff --git a/main.c b/main.c new file mode 100644 index 0000000..a3c0836 --- /dev/null +++ b/main.c @@ -0,0 +1,40 @@ +#define _GNU_SOURCE +#include +#include + // #include +#include +#include +#include +#include +#include + +#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \ + } while (0) +#define STACK_SIZE (1024 * 1024) + +int child(void* buf){ + printf("print buf (addr=%p): %s\n",buf,(char *) buf); + sleep(2); + printf("print buf (addr=%p): %s\n",buf, (char *)buf); + exit(EXIT_SUCCESS); +} + +int main(){ + char * stack = mmap(NULL, + STACK_SIZE, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, + -1, + 0); + if (stack == MAP_FAILED) + errExit("mmap"); + char * buf = malloc(256 * sizeof(char)); + snprintf(buf,256,"inital"); + int pid = clone(child, stack + STACK_SIZE,SIGCHLD | CLONE_THREAD | CLONE_SIGHAND | CLONE_VM, buf); + if (pid < 0) + errExit("failed to create child"); + sleep(1); + snprintf(buf,256,"changed"); + sleep(2); + exit(EXIT_SUCCESS); +}