I’m working on a project where I need to implement a version of the clone() API using fork(). The original context of the function is a thread-based implementation of task worker creation. Here’s the original code:
int bkwrk_create_worker() {
unsigned int i;
for (i = 0; i < MAX_WORKER; i++) {
void ** child_stack = (void ** ) malloc(STACK_SIZE);
unsigned int wrkid = i;
pthread_t threadid;
sigset_t set;
int s;
sigemptyset( & set);
sigaddset( & set, SIGQUIT);
sigaddset( & set, SIGUSR1);
sigprocmask(SIG_BLOCK, & set, NULL);
/* Stack grow down - start at top*/
void * stack_top = child_stack + STACK_SIZE;
wrkid_tid[i] = clone( & bkwrk_worker, stack_top,
CLONE_VM | CLONE_FILES,
(void * ) & i);
usleep(100);
return 0;
}
However, when I try to replace clone()
with fork()
, I run into a problem. The data between the parent and child process is not the same. If worker[i] is assigned to the parent process, then whenever the child process needs it, its task is NULL.
I understand that fork()
creates a new process with a copy of the parent’s memory, so changes in the parent’s memory after the fork()
do not affect the child. However, clone()
with the CLONE_VM flag allows the child and parent to share memory, so changes in one process are visible in the other.
How can I achieve similar behavior with fork()
? Is there a way to share specific data between the parent and child process created by fork()
?
I have already referred to the following question. What i learnt was both of the fork() and clone() API both used the clone() system call but the fork() API does not provide any argument for the stack, do I need to implement it on my own or I need to use the Inter Process Communication?