shm.hライブラリを使用して1つの共有メモリブロックを使用して2つの異なる共有を試みています。次の例を作成しました。ここでは、1つの共有メモリブロックが作成され、2つの整数を保持するのに十分な大きさです。次に、それに2つの整数を付加し、2つのプロセスを作成します。最初のプロセスは最初の整数をインクリメントします。次に、2番目のプロセスは2つの整数の値を出力します。しかし、何が起こるかというと、両方の整数が増分されます。
私は何が間違っているのですか?shmライブラリの使い方を学び始めたところです。
これはコードです:
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <stdio.h>
#include <unistd.h>
int main() {
// Declare variables
int shmID;
int *data1;
int *data2;
// Create a shared memory segment
if((shmID=shmget(IPC_PRIVATE, 2*sizeof(int), 0666 | IPC_CREAT))<0)
{
fprintf(stderr,"Problem initializing shared memory\n");
perror("main");
return -1;
}
if((data1=shmat(shmID,NULL,0))==(int *)-1)
{
fprintf(stderr,"Problem attaching memory 1\n");
perror("main");
return -1;
}
if((data2=shmat(shmID,NULL,0))==(int *)-1)
{
fprintf(stderr,"Problem attaching memory 2\n");
perror("main");
return -1;
}
printf("%p %p\n",data1,data2);
(*data1)=0;
(*data2)=0;
if(fork())
{ // Process 1 will be the incrementer
for(int i=0;i<100;i++)
{
(*data1)++;
printf("IN: %d\n",(*data1));
sleep(1);
}
printf("IN DONE\n");
}
else
{
while((*data1)<50)
{
printf("OUT: %d %d\n",(*data1),(*data2));
sleep(1);
}
printf("OUT DONE\n");
}
}
そしてこれは出力です:
0x7fcd42a97000 0x7fcd42a96000
IN: 1
OUT: 1 1
IN: 2
OUT: 2 2
IN: 3
OUT: 3 3
私はこれをGentooLinuxで実行しています。