如何共享进程fork之间的内存()? [英] How to share memory between process fork()?

查看:164
本文介绍了如何共享进程fork之间的内存()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在叉孩子,如果我们修改一个全局变量,它不会在主程序改变。

有没有办法来改变一个全局变量儿童叉?

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;INT glob_var;主(INT交流,焦炭** AV)
{
  INT PID;  glob_var = 1;  如果((PID =叉())== 0){
    / * *子/
    glob_var = 5;
  }
  其他{
    / *错误* /
    PERROR(叉);
    出口(1);
  }  INT状态;
  而(等待(安培;!状态)= PID){
  }
   的printf(%d个\\ N,glob_var); //这将显示1,而不是5。
}


解决方案

您可以使用共享内存(的shm_open() shm_unlink()的mmap(),等等)。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&; SYS / mman.h>
#包括LT&; SYS / types.h中>
#包括LT&; SYS / wait.h>
#包括LT&;&unistd.h中GT;静态INT * glob_var;INT主要(无效)
{
    glob_var = MMAP(NULL,sizeof的* glob_var,PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_ANONYMOUS,-1,0);    * glob_var = 1;    如果(叉()== 0){
        * glob_var = 5;
        出口(EXIT_SUCCESS);
    }其他{
        等待(NULL);
        的printf(%d个\\ N,* glob_var);
        在munmap(glob_var,sizeof的* glob_var);
    }
    返回0;
}

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.
}

解决方案

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;
}

这篇关于如何共享进程fork之间的内存()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆