How to share memory between processes created by fork()?
Changing a global variable is not possible because the new created process (child)is having it's own address space.
So it's better to use shmget()
,shmat()
from POSIX
api
Or You can use pthread
, since pthreads
are sharing the global
data and the changes in global variable is reflected in parent.
Then read some Pthreads tutorial.
You can use shared memory (shm_open()
, shm_unlink()
, mmap()
, etc.).
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static int *glob_var;
int main(void)
{
glob_var = mmap(NULL, sizeof *glob_var, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*glob_var = 1;
if (fork() == 0) {
*glob_var = 5;
exit(EXIT_SUCCESS);
} else {
wait(NULL);
printf("%d\n", *glob_var);
munmap(glob_var, sizeof *glob_var);
}
return 0;
}