본문 바로가기

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

IPC 기법 실습2 -Message queue

메세지 큐(Message queue)

: FIFO(First in First out) 정책으로 데이터 전송 

: 양방향 통신이 가능하다 (key값으로 메세지를 전송하고 받을 수 있다)

 

msqid=msgget(key,msgflg) : 메세지큐를 하나 생성 msgget() 시스템콜 이용

key:1234(다른메세지큐와 구분된 정수값으로 설정),

msgflg는 옵션 (IPC_CREAT|접근권한 : 새로운 키면 식별자로 새로 생성)

msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) : 메세지 큐를 보낼 때 사용하는 msgsnd() 시스템콜 이용

msgflg 설정 : 블록모드(0):상대방이 읽을 때까지 코드가 멈춰있다, 비블록모드(IPC_NOWAIT):상대방이 읽지 않아도 다음코드를 실행

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg)

: 메세지 큐를 받을 때 사용하는 msgrcv() 시스템콜

msgtyp : 0이면 첫번째 메세지, 양수이면 타입이 일치하는 첫번째 메세지

msgflg 설정 : 블록모드(0)/ 비블록모드(IPC_NOWAIT)

ex) mesgrcv(msqid, &rbuf, MSGSZ, 1, 0)

 

메시지 큐 코드 예제

msgsnd

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>

typedef struct msgbuf{
	long type;
	char text[50];
} MsgBuf;

int main(void){
	int msgid, len;
	MsgBuf msg;
	key_t key=1234;
	msgid=msgget(key,IPC_CREAT|0644);
	if(msgid==-1){
		perror("msgget");
		exit(1);
	}
	msg.type=1;
	strcpy(msg.text,"Hello Message Queue\n");
	if(msgsnd(msgid, (void *)&msg,50,IPC_NOWAIT==-1)){
			perror("msgsnd");
			exit(1);
	}
		return 0;
}

msgrcv

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>

typedef struct msgbuf{
long type;
char text[50];
} MsgBuf;

int main(void){
	MsgBuf msg;
	int msgid, len;
	key_t key=1234;
	if((msgid=msgget(key,IPC_CREAT|0644))<0){
		perror("msgget");
		exit(1);
	}
	len=msgrcv(msgid,&msg,50,0,0);
	printf("Received Message is [%d] %s\n",len,msg.text);
	return 0;
}

 

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

ipcs 명령어  (0) 2021.10.03
참고 ftok() 키생성을 위한 함수  (0) 2021.10.03
IPC 기법 실습1 -pipe  (0) 2021.10.03
다양한 IPC 기법  (0) 2021.10.03
프로세스 스케쥴링 (운영체제의)  (0) 2021.10.03