I’m trying to use a clone() syscall to create a thread which shares resources with the parent process.
In the book I read that if I use the following flags, I will be able to do so:
CLONE_VM | CLONE_FILES | CLONE_SIGHAND | CLONE_FS
But it seems the variables are not being shared.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <linux/sched.h>
#include <string.h>
#define STACK_SIZE 65536
#define BUFSIZE 200
int n = 5;
int Child(void *);
int main() {
pid_t pid;
char *stack;
stack = malloc(STACK_SIZE);
pid = clone(Child,stack + STACK_SIZE, CLONE_SIGHAND|CLONE_FS|CLONE_VM|CLONE_FILES);
wait(NULL);
char buf[BUFSIZE];
sprintf(buf,"Back to parent: Value of n: %d\n",n);
write(1,buf,strlen(buf));
return 0;
}
int Child(void *args) {
n += 15;
char buf[BUFSIZE];
sprintf(buf,"In child: Value of n: %d\n",n);
write(1,buf,strlen(buf));
}
The output keeps changing as well. I’m confused.
You have two variables called
n.Childoperates on the global one, butmainuses the one defined in its scope.You should also change your
waitcall towaitpid(-1, NULL, __WALL), otherwise you won’t actually wait on the cloned process. (Or you could add|SIGCHLDto the clone options.)From the
clone(2)docs: