1つの共有メモリで2つの変数A,Bを扱うにはどうすればいいでしょうか?
shmgetで共有メモリを確保しています。
同じ共有メモリIDでA,Bという変数を別々に扱いたいのですが、方法はありますでしょうか?
C
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <string.h> int main (int argc, char *argv[]) { int id, tmp, i; int *counter; int num=1; int A=100, B=0; struct shmid_ds buf; srand ((unsigned) time (NULL)); if (argc == 1) { /* 引数がない場合は共有メモリを確保 */ if ((id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666)) == -1) { perror("shmget"); exit(EXIT_FAILURE); } printf("shared memory ID = %d\n", id); } else if (argc == 2) { /* 第1引数に共有メモリIDが指定された場合 */ id=atoi(argv[1]); } else { fprintf(stderr, "%s [<shared memory ID>] \n", argv[0]); exit(EXIT_FAILURE); } /* 共有メモリ領域を counter にアタッチ */ counter = (int *) shmat (id,0,0); if (argc == 1) *counter = 0; for (i = 0; i < 100; i++) { /* 100回移動をくり返す */ fprintf(stderr, "A = %d, ", A); sleep(rand()%4); A-=num; *counter=A; fprintf(stderr, "B = %d ", B); sleep(rand()%4); B+=num; *counter=B; } shmctl (id, IPC_STAT,&buf); if(shmdt(counter)==-1) { /* デタッチ */ perror("shmdt"); exit(EXIT_FAILURE); } if (buf.shm_nattch==1) { if (shmctl (id, IPC_RMID, 0) == -1) { perror ("chmctl"); } } }
まだ回答がついていません
会員登録して回答してみよう