共有メモリのサイズを大きくする必要があります。どのくらいの配列が必要ですか?どのような価値であれ、共有メモリセグメントを作成する前にそれを選択する必要があります。ダイナミックメモリはあまりうまく機能しません。
共有メモリに接続すると、開始アドレスへのポインタが得られます。どのような目的にも使用できるように十分に整列しています。共有メモリにアクセスするためのポインタの使用に注意してください:
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);
どちらのオペレーティングシステムを使用していますか? –
私の間違い。これはLinux上にあります – Josh
昨日からのこの質問に注意してください:http://stackoverflow.com/questions/1664519/creating-accessing-shared-memory-in-c(Sys V IPCを選択しましたが、同じ一般的な件名です)。 –