반응형
프로세스 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()
에서 POSIX
API를
또는 당신은 사용할 수 pthread
있기 때문에, pthreads
공유되는 global
데이터를 글로벌 변수의 변화가 부모에 반영됩니다.
참조 URL : https://stackoverflow.com/questions/13274786/how-to-share-memory-between-process-fork
반응형
'programing' 카테고리의 다른 글
확장 된 WAR 파일의 장점 / 단점 (0) | 2021.01.15 |
---|---|
Java 6 및 Java 7에서 다르게 작동하는 intern () (0) | 2021.01.15 |
강제 다운로드 대신 AWS S3 디스플레이 파일 인라인 (0) | 2021.01.15 |
입력하는 동안 UITextField 크기 조정 (자동 레이아웃 사용) (0) | 2021.01.15 |
ggplot2에서 글꼴 변경 (0) | 2021.01.14 |