Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share memory between processes created by fork()?

Tags:

c

fork

In fork child, if we modify a global variable, it will not get changed in the main program.

Is there a way to change a global variable in child fork?

#include <stdio.h> #include <stdlib.h> #include <unistd.h>  int glob_var;  main (int ac, char **av) {   int pid;    glob_var = 1;    if ((pid = fork()) == 0) {     /* child */     glob_var = 5;   }   else {     /* Error */     perror ("fork");     exit (1);   }    int status;   while (wait(&status) != pid) {   }    printf("%d\n",glob_var); // this will display 1 and not 5. } 
like image 838
MOHAMED Avatar asked Nov 07 '12 17:11

MOHAMED


People also ask

Does a forked process share memory?

After fork the parent and child can update their own copies of the variables in their own way, since they dont actually share the variable. Here we show how they can share memory, so that when one updates it, the other can see the change.

What is shared between forked processes?

Answer: Only the shared memory segments are shared between the parent process and the newly forked child process. Copies of the stack and the heap are made for the newly created process.

What happens once a fork () system is called by a process?

The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child.


2 Answers

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; } 
like image 185
md5 Avatar answered Nov 07 '22 13:11

md5


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 pthreadsare sharing the globaldata and the changes in global variable is reflected in parent.

Then read some Pthreads tutorial.

like image 38
Omkant Avatar answered Nov 07 '22 14:11

Omkant