linux ipc (shared memory)
linux app 간 통신이 필요해서 통신 방법을 찾다보니. .일단.. shared memory방식이 있어서 정리 합니다.
의외로 구현도 쉽고 확인도 쉽네요 ^^;
sample code : 5678 키로 만들고 해당 키로 만든 shared memory에 쓰고 읽어가는 코드 입니다.
1 host.c +
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include
- #include
- #include
- #include
- int main(int argc, char **argv)
- {
- int shmid;
- void *shared_memory = (void *)0;
- int skey = 5678;
- int *write_shm;
- // 공유메모리 공간을 만든다.
- shmid = shmget((key_t)skey,
-
sizeof(int), 0666 IPC_CREAT); - if(shmid == -1)
- {
- perror(“shmget failed : “);
- exit(0);
- }
- printf(“Key %x\n”, skey);
- // 공유메모리를 맵핑한다.
- shared_memory = shmat(shmid, (void *)0, 0);
- if(!shared_memory)
- {
- perror(“shmat failed : “);
- exit(0);
- }
- write_shm = (int *)shared_memory;
- *write_shm = 100;
- }
1 client.c
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include
- #include
- #include
- #include
- int main(int argc, char **argv)
- {
- int shmid;
- int skey = 5678;
- int *shared_memory;
- shmid = shmget((key_t)skey, sizeof(int), 0666);
- if(shmid == -1)
- {
- perror(“shmget failed\n”);
- exit(0);
- }
- shared_memory = shmat(shmid, (void *)0, 0);
- if(!shared_memory)
- {
- perror(“shmat failed : “);
- exit(0);
- }
- printf(“shm id : %d\n”, shmid);
- while(1)
- {
- int num = *shared_memory;
- printf(“key[%d] : read shm data : %d\n”, skey, num);
- sleep(1);
- }
- }
shared memory 할당 확인
$ipcs -m
- pi@raspberrypi:~ $ ipcs -m
- —— Shared Memory Segments ——–
- key shmid owner perms bytes nattch status
- 0x00000000 163840 pi 600 393216 2 dest
- 0x00000000 1033994241 pi 600 393216 2 dest
- 0x00000000 327682 pi 600 393216 2 dest
- 0x0000162e 1892384771 pi 666 4 0
- 0x00000000 517242885 pi 600 393216 2 dest
- 0x00000000 1908146182 pi 600 524288 2 dest
- 0x00000000 280428551 root 777 1228800 2 dest
- 0x00000000 1854996488 root 600 3686400 1 dest
ref : https://www.joinc.co.kr/w/Site/system_programing/Book_LSP/ch08_IPC