본문 바로가기

Computer Science/시스템프로그래밍2

IPC 기법 실습3 -공유메모리(Shared Memory)

: kernel space에 메모리 공간을 만들고, 해당 공간을 변수처럼 쓰는 방식

(커널에 있는 공간을 변수로 맵핑 시켜서 해당 데이터를 참조하는 방식)

: 공유메모리 key를 가지고, 여러 프로세스 접근 가능

 

1. 공유 메모리 생성

int shmget(key_t key, size_t size, int shmflg);

key : 임의 숫자 또는 ftok 함수로 생성한 키값

size : 공유 메모리 크기

shmflg : 공유 메모리 속성

리턴값 : 공유 메모리 식별자 리턴

 

shmid=shmget((key_t)1234,SIZE,IPC_CREAT|0666))

 

2. 공유 메모리 연결

void *shmat(int shmid, const void *shmaddr, int shmflg);

shmid : shmget 함수로 생성한 공유 메모리 식별자

shmaddr : 공유 메모리 연결 주소 (보통 (char *)NULL으로 설정하면, 알아서 적절한 주소로 연결)

shmflg : 공유 메모리의 읽기/쓰기 권한 (0이면 읽기/쓰기 가능, SHM_RDONLY면 읽기만 가능)

리턴값 : 성공시 연결된 공유 메모리의 시작 주소를 리턴 

 

shmaddr=(char *)shmat(shmid,(char *)NULL, 0)

 

3. 공유 메모리 해제

int shmdt(char *shmaddr);

 

읽기 쓰기는 포인터 처럼 변수처럼 사용하면 됨

4. 공유 메모리에서 읽기

printf("%s\n", (char *)shmaddr)

 

5. 공유 메모리에서 쓰기

printf((char *)shmaddr, "Linux Programming")

 

6. 공유메모리 삭제

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

shmid : shmget 함수로 생성한 공유 메모리 식별자

cmd : 수행할 제어 기능 ex) IPC_RMID : shmid로 지정한 공유 메모리 제거

buf : 제어 기능에 사용되는 공유 메모리 구조체의 구조

shmctl(shmid, IPC_RMID, (struct shmid_ds *)NULL);

 

실습

#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void){
	int shmid, pid;
	char *shmaddr_parent, *shmaddr_child;
	//공유메모리 생성shmget()
	shmid=shmget((key_t)1234,10,IPC_CREAT|0644);
	if (shmid==-1){
		perror("shmget error\n");
		exit(1);
	}
	pid=fork();
	if(pid>0){
		wait(0);
		//공유메모리 연결 shmat()
		shmaddr_parent=(char *)shmat(shmid,(char *)NULL,0);
		printf("%s\n",shmaddr_parent);
		//공유메모리 해제shmdt
		shmdt((char *)shmaddr_parent);
	}
	else{
		shmaddr_child=(char *)shmat(shmid,(char *)NULL,0);
		strcpy((char *)shmaddr_child, "Hello Parent!");
		shmdt((char *)shmaddr_child);
		exit(0);
	}

	//공유 메모리 삭제 shmctl()
	shmctl(shmid, IPC_RMID, (struct shmid_ds *)NULL);
	return 0;
}

'Computer Science > 시스템프로그래밍2' 카테고리의 다른 글

시그널과 프로세스  (0) 2021.10.03
시그널(signal)  (0) 2021.10.03
msgctl(): 메세지 큐를 컨트롤 한다  (0) 2021.10.03
ipcs 명령어  (0) 2021.10.03
참고 ftok() 키생성을 위한 함수  (0) 2021.10.03