2008/03/28

message queue example

多年來,在做嵌入式產品時,經驗上在網虎時代大家都用 message queue 機制來通訊,其實當時也還有其他的機制,但是底下的工具可以讓大家省點事,似乎後來就都採用這套方法,有興趣的人可以拿去用用看。

語法在程式中有提到




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

#define MAX_TEXT 255

typedef struct my_msg_st {
long int mtype;
char mtext[MAX_TEXT];
} msgbuf;

int main(int argc, char *argv[])
{
int msgid;
int sz;
int key;
long int type;
msgbuf mdata;
char buffer[MAX_TEXT];

if (argc == 1) {
printf ("Usage: %s key [type [data]]\n", argv[0]);
return 1;
}

key = atoi (argv[1]);
msgid = msgget((key_t)key,0666|IPC_CREAT);

if (msgid == -1) {
return 2;
}

if (argc == 2) { // get all types
if (msgrcv(msgid,(void *)&mdata, MAX_TEXT, (long)0, IPC_NOWAIT) == -1) {
return 3;
}
printf ("%d %s\n", mdata.mtype, mdata.mtext);
}
else if (argc == 3) { // get assign type
type = atol (argv[2]);
if (msgrcv(msgid,(void *)&mdata, MAX_TEXT, type, IPC_NOWAIT) == -1) {
return 4;
}
printf ("%ld %s\n", mdata.mtype, mdata.mtext);
}
else if (argc == 4) { // send assign type, data
mdata.mtype = atol(argv[2]);
strcpy (mdata.mtext, argv[3]);
mdata.mtext[strlen(mdata.mtext)] = '\0';
if (msgsnd (msgid, (void *)&mdata, MAX_TEXT, IPC_NOWAIT) == -1 ) {
return 5;
}
printf ("send to msg_id %d with type %ld : '%s'\n", msgid, (long)mdata.mtype, mdata.mtext);
}
return 0;
} // end of main()

0 意見: