문제

저는 어린이 프로세스가 Linux에서 서로 의사 소통하는 프로그램을 작성하려고합니다.

이러한 프로세스는 모두 동일한 프로그램에서 생성되므로 코드를 공유합니다.

정수 배열뿐만 아니라 두 개의 정수 변수에 액세스해야합니다.

나는 공유 메모리가 어떻게 작동하는지 모르고 내가 검색 한 모든 자원이 나를 혼란스럽게하는 것 외에는 아무것도하지 않았다.

모든 도움이 크게 감사드립니다!

편집 : 여기에 하나의 int를 공유하기 위해 지금까지 작성한 일부 코드의 예는 있지만 아마도 잘못되었을 것입니다.

int segmentId;  
int sharedInt;  
const int shareSize = sizeof(int);  
/* Allocate shared memory segment */  
segmentId = shmget(IPC_PRIVATE, shareSize, S_IRUSR | S_IWUSR);  

/* attach the shared memory segment */    
sharedInt = (int) shmat(segmentId, NULL, 0);  

/* Rest of code will go here */  

/* detach shared memory segment */  
shmdt(sharedInt);  
/* remove shared memory segment */  
shmctl(segmentId, IPC_RMID, NULL);
도움이 되었습니까?

해결책

공유 메모리의 크기를 늘려야합니다. 배열이 얼마나 큰가요? 가치가 무엇이든, 공유 메모리 세그먼트를 만들기 전에 선택해야합니다. 동적 메모리는 여기서는 잘 작동하지 않습니다.

공유 메모리에 연결하면 시작 주소에 대한 포인터가 나타납니다. 어떤 목적 으로든 사용하기에 충분히 잘 정렬 될 것입니다. 따라서 두 가지 변수에 포인터를 만들고이 선을 따라 배열을 만들 수 있습니다 (코드 예제에서 골격의 일부를 구제) - 공유 메모리에 액세스하기 위해 포인터를 사용하십시오.

enum { ARRAY_SIZE = 1024 * 1024 };
int segmentId;  
int *sharedInt1;
int *sharedInt2;
int *sharedArry;

const int shareSize = sizeof(int) * (2 + ARRAY_SIZE);  
/* Allocate shared memory segment */  
segmentId = shmget(IPC_PRIVATE, shareSize, S_IRUSR | S_IWUSR);  

/* attach the shared memory segment */    
sharedInt1 = (int *) shmat(segmentId, NULL, 0);
sharedInt2 = sharedInt1 + 1;
sharedArry = sharedInt1 + 2;

/* Rest of code will go here */
...fork your child processes...
...the children can use the three pointers to shared memory...
...worry about synchronization...
...you may need to use semaphores too - but they *are* complex...
...Note that pthreads and mutexes are no help with independent processes...  

/* detach shared memory segment */  
shmdt(sharedInt1);  
/* remove shared memory segment */  
shmctl(segmentId, IPC_RMID, NULL);

다른 팁

이 안내서는 유용합니다. http://www.cs.cf.ac.uk/dave/c/node27.html. 몇 가지 예제 프로그램이 포함되어 있습니다.

또한 있습니다 Linux Man Pages 온라인.

당신의 의견에서 그것은 당신이 사용하고있는 것 같습니다 IPC_PRIVATE, 그리고 그것은 분명히 잘못 보인다 ( "개인"종류의 종류는 공유를위한 것이 아니라고 제안한다. 다음과 같은 것을 시도하십시오.

#include <sys/ipc.h>
#include <sys/shm.h>

...

int segid = shmget((key_t)0x0BADDOOD, shareSize, IPC_CREAT);
if (segid < 0) { /* insert error processing here! */ }
int *p = (int*) shmat(segid, 0, 0);
if (!p) { /* insert error processing here! */ }

공유 메모리는 고유 한 ID로 한 프로세스로 할당 된 메모리의 세그먼트 일 뿐이며 다른 프로세스는 동일한 ID로 할당을 만들고 메모리의 크기는 사용중인 구조의 크기입니다. 2 개의 정수와 정수 배열이있는 구조가 있습니다.

이제 그들은 둘 다 같은 기억에 대한 포인터를 가지고 있으므로, 한 사람의 글은 다른 것이 무엇이든 덮어 쓰고, 다른 하나는 즉시 접근 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top