Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c - How to share memory between processes created by 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
",glob_var); // this will display 1 and not 5.
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", *glob_var);
        munmap(glob_var, sizeof *glob_var);
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...