programing

프로세스 fork ()간에 메모리를 공유하는 방법은 무엇입니까?

projobs 2021. 1. 15. 07:29
반응형

프로세스 fork ()간에 메모리를 공유하는 방법은 무엇입니까?


fork child에서 전역 변수를 수정하면 메인 프로그램에서 변경되지 않습니다.

자식 포크에서 전역 변수를 변경하는 방법이 있습니까?

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

당신은 (공유 메모리를 사용할 수 shm_open(), shm_unlink(), mmap(), 등).

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

새로 생성 된 프로세스 (자식)에 자체 주소 공간이 있으므로 전역 변수를 변경할 수 없습니다.

그래서 사용하는 것이 좋습니다 shmget(), shmat()에서 POSIXAPI를

또는 당신은 사용할 수 pthread있기 때문에, pthreads공유되는 global데이터를 글로벌 변수의 변화가 부모에 반영됩니다.

참조 URL : https://stackoverflow.com/questions/13274786/how-to-share-memory-between-process-fork

반응형