Skip to main content

Interprocess Communication or IPC, Message Queue

Unix에서의 interporcess의 통신에는
여러가지가 있다.

그 대표적인 것으로,
pipes or FIFOS,
message queues
semaphores
shared memory
sockets
streams이 있다.

그 중에서 Message Queues에 대해서 알아보자


ipcs -q로, kernel에 존재하는 Message Queues를 확인할 수 있다.

msgget으로 새로운 큐가 생성되거나, 존재하는 큐를 획득할 수 있다.
msgsnd로 의해 발생한 새로운 메세지는 queue의 끝에 추가된다
msgrcv로 의해 메세지를 first-in, first-out order로 fetch된다.

MSGMAX, 2048bytes the size of the largest message.
MSGMNB, 4096bytes the maximum size of a particular queue
MSGMNI, 50 the maximum number of messages queues.
MSGTQL, 40 the maximum number of messages

Initialising the Message Queue


#include &lt sys/types.h &gt
#include &lt sys/ipc.h&gt
#include &lt sys/msg.h&gt

int msgget(key_t key, int msgflag);

msgflag는 octal integer이고 Queue's permission and control flags이다
IPC_CREAT
IPC_EXCL
만 사용가능
IPC_EXCL지정후, IPC structure가 이미 존재할 경우, EEXIST에러발생


msgget
실패시, -1
성공시, nonnegative message queue ID

이 id는 다른 함수에서 사용할 수 있다.

send쪽에서는 msgget(key, IPC_CREAT | 0666);으로 하고
recv쪽에서는 msgget(key, 0666)으로 한다.

그리고, send를 하면, kernel의 message queue에 메세지로 저장되고,
그 메세지를 msgrcv로 얻어온다.


Controlling message queues

msgctl(int msqid, int cmd, struct msqid_ds *buf)

cmd
IPC_STAT; 큐의 속성을 msqid_ds struct로 적용
IPC_SET; msg_perm.uid, msg_perm.gid, msg_perm.mod, msg_qbytes의 속성만 변경
단 실행하는 user id가 msg_perm.cuid, msg_perm.uid와 동일할때만 적용됨
IPC_RMID; message queue를 삭제,
단 실행하는 user id가 msg_perm.cuid, msg_perm.uid와 동일할때만 적용됨

Sending and Receiving Messages

msgsnd(int msqid, const void *ptr, size_t nbytes, int flag);
msgsnd에 의해 메세지를 message queue에 놓인다

ptr coontains the positive integer message type, and it is immediately followed by the message data.

struct mymesg{
long mtype; // positive message type
char mtext[512]; // message data, of length nbytes
};

flag는 IPC_NOWAIT
만약, queue가 full일 경우, EAGAIN이라는 에러를 발생시키고.

msgrcv에서
flag를 IPC_NOWAIT로 할 경우, message를 기다리지 않는다.
그러나, 0으로 설정할 경우, 만약 queue에 message를 없을 경우, message를 기다린다.

msgsnd에서는 IPC_NOWAIT로 하나 0으로 하나 변화없음.


msgrcv(int msqid, void *ptr, size_t nbytes, long type, int flag);

msgrcv; retrieve messages from a queue
성공시 size of data portion of message
실패시, -1
type ==0 the first message on the queue is returned. (first-in, first-out)
type > 0 the first message on the queue whose message type equals type is returned.
type < 0 the first message on the queue whose message type is the lowest value less than or equal to the absolute value of type is returned.

Comments

Popular posts from this blog

맥OS 사전에 사전 파일 추가하기

1. http://code.google.com/p/mac-dictionary-kit/에서 sdconv를 다운로드 받는다. 2. e4u 등과 같은 사전 파일(stardict 형식)을 다운받는다. 3. 사전 파일의 압축을 풀면, e4u.ifo, e4u.dict.dz, e4u.idx와 같은 파일이 보인다. 4. sdconv 디렉터리 내의 convert 실행 파일로 convert e4u.ifo를 실행한다. 5. 위 과정이 완료되면 아래와 같이 사전에 e4u가 추가된 점을 확인할 수 있다. 6. 순서를 조절하여 사용하면 된다.

Sqlite database is locked

sqlite는 embedded system에서 널리 사용되는 무료 dbms?(dbms라고 말하긴 좀 그렇지만, dbms라 불러주자 ㅎ) 이다. 특히 memory db 기능이 아주 유용하다. 그 밖의 dbms에서도 이 기능이 있으나, 이 기능이 지원되는 버전은 대부분 고가이다. 따라서, 무료인 sqlite를 많이들 애용하는 것 같다. 멀티쓰레드를 sqlite DB를 구현하고 롱런테스트를 하다보면, pthread_mutex_lock으로 쓰레드 간의 교착상태를 막아줘도, sqlite lock 에러가 간헐적으로 발생할 것이다. 이에 대해 본인은 다음과 같은 에러 처리 구문을 준비하여 사용하고 있다. sqlite Error가 발생하면, sqlite3_exception함수를 호출한다. 이 함수에서 sqlite error code를 구분하여, 만약, busy 또는 locked이면 최대 2초간 sleep 상태로 만드는 sqlite3_busy_timeout, busy handler를 호출한다. 그 다음, goto 구문으로 재차 sqlite3_exec를 실행한다. 단, sqlite3_exec는 transaction의 begin과 commit 또는 rollback 구문 사이에서 실행한다. 대부분 lock 에러가 발생하더라도 1~2번 실패 후에, 처리된다는 것이 본인의 테스트 결과이다. 단, journal를 WAL로 변경하였음. 기존 journal은 멀티쓰레드 지향적이지 않다는 점을 잊지마시길.... Error Code SQLITE_LOCKED (6): Database Is Locked This error code occurs when you try to do two incompatible things with a database at the same time from the same database connection. For example, if you are in the middle of a SELECT statement and you t

SAStruts란

SAStruts 개요 Struts는 Spring Framework 다음으로 많이 사용되고 있는 FrameWork이다. Struts는 프레임워크로 강력한 기능을 제공한다. 하지만, 개발 과정에서 부수적인 설정 작업이 개발자들을 힘들게 했다. 이 문제를 해결하기 위해, 일본 개발자 커뮤니티 Seasar(일본 오키나와의 전설 동물, 우리나라의 해태와 비슷^^) 에서 개발한 프레임워크가 SAStruts(Super Agile Struts)이다. 아래 아키텍처 그림과 같이, SAStruts의 모태는 Struts이다. 다만, 상기한 복잡하고 까다로운 설정 작업을 그림2와 같이 SAStruts가 개발자 대신 내부적으로 처리해 준다. 예를 들어, Struts는 항상 struts-config.xml을 읽고 Action 클래스를 호출한다. 이 때문에, 개발자는 소스 코드를 수정한 후, 늘 struts-c onfig.xml 파일을 검토 또는 수정해야 한다. 또한, 대형 프로젝트일 경우는, 이 struts-config.xml 파일이 경합을 자주 일으킨다. 이는 실로 개발자의 스트레스 치수를 높이는 원인이다. 반면, SAStruts는 이 번거로운 작업을 알아서 처리해 준다. 아리가또~~~ 입니다. 그림1 Struts 아키텍처 그림2 SAStruts 아키텍처 그럼, 이 번거로운 작업을 SAStruts는 어떻게 처리하는 것인지 궁금할 것이다. 그것은 Java의 annotation기술을 이용한 점이다. 예를 들어, @Execute, @ActionForm, @Resource 등 Seasar 커뮤니티에서 제공하는 Dolteng 플러그인을 사용하면, SAStruts 개발이 더욱 효율적이다. SAStruts 프로젝트는 다음과 같은 패키지 구조로 형성된다. [root package].action Action 클래스 [root package].condition 데이터베이스에 엑세스하는 조건 설정 [root packa