Yesterday, I learned Socket: I started learning Queue today. The following is queue.c code ************************************************** ************************** # incrude
#define msg_max 4056 // <= 4056 max size of message (bytes)
/ * Message Buffer for msgsnd and msgrcv calls * / / / defined information struct smsgbuf {long mtype; // type of message long moduleId; // module id char mText [MSG_max]; // message text * /};
// Create queueint open_queue (key_t keyval) {INT QID; if ((qid = msgget (keyval, ipc_creat | 0660)) == -1) {RETURN (-1);} return (qid);}
// send queue message // qid = queue id // qbuf = send message bufferint send_message (int qid, struct sMsgBuf * qbuf) {int result, length; / * The length is essentially the size of the structure minus sizeof (mtype) * / Length = SIZEOF (Struct SMSGBUF) - SIZEOF (long); ((Result = MSGSND (QID, QBUF, Length, 0)) == -1) {RETURN (-1);} return (result);} // read queue message // qid = queue id // type = message type // qbuf = read message buffer // return int = err codeint read_message (int qid, long type, struct sMsgBuf * qbuf) {int result, length; / * The length is essentially the size of the structure minus sizeof (mty) * / length = sizeof (Struct smsgbuf) - sizeof (long); if ((Result = MSGRCV (QID, QBUF, Length, Type, 0)) = = -1) {return (-1);} return (result);} // check if the queue has a message INT peek_message (int}) {int result, length; // ignore the address and length of the buffer . In this way, the system call will fail. Despite this, // can check the returned E 2 B I g value, which means that the requirements that meet the conditions do exist. IF ((Result = MSGRCV (QID, NULL, 0, TYPE, IPC_NOWAIT) == -1) {if (errno == e2big) Return 1;} Return 0;} // sample queueint createque () {INT QID; Key_t msgkey;
Struct smsgbuf msgbuf; / * generate out ipc key value * / msgKey = ftok (".", 'm'); / * open / create the queue * / if ((qid = open_queue (msgKey)) == -1) {Perror ("open_queue"); exit (1);} msgbuf.mtype = 1; msgbuf.moduleId = 100; strcpy (msgbuf.mtext, "love"); if ((Send_Message (QID, & msGbuf) == - 1) {PERROR ("send_message"); exit (1);}}
INT GET_QUEUE_DS (INT QID, STRUCT MSQID_DS * QBUF) {IF (MsgcTl (QID, IPC_STAT, QBUF) == -1) {RETURN (-1);} return (0);} int change_queue_mode (int qid, char * mode) ) {struct msqid_ds tmpbuf; / * Retrieve a current copy of the internal data structure * / get_queue_ds (qid, & tmpbuf); / * Change the permissions using an old trick * / sscanf (mode, "% ho", & tmpbuf.msg_perm. Mode); / * Update the internal data structure * / if (MsgcTl (QID, IPC_SET, & TMPBUF) == -1) {RETURN (-1);} Return (0);} int REMOVE_QUEUE (INT QID) {IF MSGCTL (QID, IPC_RMID, 0) == -1) {RETURN (-1);} return (0); // (void) MSGCTL (QID, IPC_RMID, 0);} ********* ********************************************************