Created
November 2, 2012 01:20
-
-
Save saiias/3998045 to your computer and use it in GitHub Desktop.
SHMのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* shared memoryのサンプルコード | |
* shared memoryを参照し,メモリに格納されている文字列(char*)を表示する | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/ipc.h> | |
#include <sys/shm.h> | |
#define SHM_SIZE 512 //byte | |
#define SHM_MODE (SHM_R | SHM_W) //読み書き可能 | |
int shm_init() | |
{ | |
/* SHM_SIZEバイトの共有メモリを準備し、ユーザに読み書きを許可する(SHM_MODE)*/ | |
int id; | |
id = shmget(IPC_PRIVATE,SHM_SIZE,SHM_MODE); | |
if(id < 0){ | |
perror("malloc error"); | |
exit(-1); | |
} | |
return id; | |
} | |
void shm_free(int shmid) | |
{ | |
//メモリの解放 | |
if(shmctl(shmid , IPC_RMID , 0) == -1){ | |
perror("SHM_RECEIVER:release error"); | |
exit(-1); | |
} | |
} | |
void shm_access(int shmid,char* adr) | |
{ | |
if((adr = (char *)shmat(shmid,NULL,0)) == (void *) -1){ | |
perror("SHM_RECEIVER:shm_access error"); | |
}else{ | |
//まず"HELLO"と書き込み、表示する | |
strcpy(adr,"HELLO"); | |
printf("%s\n",adr); | |
//shm_writerが共有メモリに書き込むまで待つ | |
while(!strcmp(adr,"HELLO")){ | |
sleep(1); | |
} | |
//共有メモリに書き込まれた文字列を表示する | |
printf("%s\n",adr); | |
if(shmdt(adr) == -1){ | |
perror("SHM_RECEIVER:shmdt error"); | |
} | |
} | |
} | |
int main(void) | |
{ | |
//他のプロセスとメモリを共有するためのID | |
int shmid; | |
char *adr; | |
//shmの初期化 | |
shmid = shm_init(shmid); | |
//shm_writerで使うためshmidを表示する | |
printf("SHMID = %d\n",shmid); | |
//shmの読み書き | |
shm_access(shmid,adr); | |
//shmの解放 | |
shm_free(shmid); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment