1つの共有メモリで2つの変数A,Bを扱うにはどうすればいいでしょうか?
shmgetで共有メモリを確保しています。
同じ共有メモリIDでA,Bという変数を別々に扱いたいのですが、方法はありますでしょうか?
C
1#include <stdio.h> 2#include <sys/types.h> 3#include <sys/ipc.h> 4#include <sys/shm.h> 5#include <stdlib.h> 6#include <string.h> 7 8int main (int argc, char *argv[]) 9{ 10 int id, tmp, i; 11 int *counter; 12 int num=1; 13 int A=100, B=0; 14 struct shmid_ds buf; 15 16 srand ((unsigned) time (NULL)); 17 if (argc == 1) 18 { /* 引数がない場合は共有メモリを確保 */ 19 if ((id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666)) == -1) 20 { 21 perror("shmget"); 22 exit(EXIT_FAILURE); 23 } 24 printf("shared memory ID = %d\n", id); 25 } 26 else if (argc == 2) 27 { /* 第1引数に共有メモリIDが指定された場合 */ 28 id=atoi(argv[1]); 29 } 30 else 31 { 32 fprintf(stderr, "%s [<shared memory ID>] \n", argv[0]); 33 exit(EXIT_FAILURE); 34 } 35 36 /* 共有メモリ領域を counter にアタッチ */ 37 counter = (int *) shmat (id,0,0); 38 if (argc == 1) *counter = 0; 39 40 for (i = 0; i < 100; i++) 41 { /* 100回移動をくり返す */ 42 fprintf(stderr, "A = %d, ", A); 43 sleep(rand()%4); 44 A-=num; *counter=A; 45 fprintf(stderr, "B = %d ", B); 46 sleep(rand()%4); 47 B+=num; *counter=B; 48 } 49 shmctl (id, IPC_STAT,&buf); 50 if(shmdt(counter)==-1) 51 { /* デタッチ */ 52 perror("shmdt"); 53 exit(EXIT_FAILURE); 54 } 55 if (buf.shm_nattch==1) 56 { 57 if (shmctl (id, IPC_RMID, 0) == -1) 58 { 59 perror ("chmctl"); 60 } 61 } 62} 63
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。