Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------------- mymsg.c
- #ifndef __MYMSG_H__
- #define __MYMSG_H__
- #include<string.h>
- #include<time.h>
- #include<sys/ipc.h>
- #include<sys/msg.h>
- #include<sys/errno.h>
- #define MSGPERM 0600 // msg queue permission
- #define MSGTXTLEN 128 // msg text length
- #define MSGKEY 32769
- struct msg_buf {
- long mtype;
- char mtext[MSGTXTLEN];
- int len;
- } msg;
- #endif
- //---------------- send.c
- #include <stdio.h>
- #include "mymsg.h"
- #include <sys/types.h>
- #include <unistd.h>
- //extern int errno;
- int get_queue_ds( int qid, struct msqid_ds *qbuf )
- {
- if( msgctl( qid, IPC_STAT, qbuf) == -1){
- return(-1);
- }
- return(0);
- }
- int main(int argc, char **argv)
- {
- int msgqid, rc;
- msgqid = msgget(MSGKEY, MSGPERM|IPC_CREAT|IPC_EXCL);
- if (msgqid < 0) {
- perror(strerror(errno));
- printf("failed to create message queue with msgqid = %d\n", msgqid);
- return 1;
- } else
- printf("message queue %d created\n",msgqid);
- // message to send
- msg.mtype = 1; // set the type of message
- msg.len = sizeof(msg)-sizeof(long);//getpid();
- sprintf (msg.mtext, "%s\n", "a text msg..."); /* setting the right time format by means of ctime() */
- printf ("a len msg = %d\n", msg.len); /* setting the right time format by means of ctime() */
- // send the message to queue
- rc = msgsnd(msgqid, &msg, sizeof(msg)-sizeof(long), 0); // the last param can be: 0, IPC_NOWAIT, MSG_NOERROR, or IPC_NOWAIT|MSG_NOERROR.
- if (rc < 0) {
- perror( strerror(errno) );
- printf("msgsnd failed, rc = %d\n", rc);
- return 1;
- } else
- printf("Message send done!\n");
- return 0;
- }
- //---------------- recv.c
- #include <stdio.h>
- #include "mymsg.h"
- int main(int argc, char **argv)
- {
- int msgqid, rc;
- msgqid = msgget(MSGKEY, MSGPERM|IPC_EXCL);
- if (msgqid < 0) {
- perror(strerror(errno));
- printf("failed to create message queue with msgqid = %d\n", msgqid);
- return 1;
- } else
- printf("message queue %d created\n", msgqid);
- // read the message from queue
- rc = msgrcv(msgqid, &msg, sizeof(msg)-sizeof(long), 0, 0);
- if (rc < 0) {
- perror( strerror(errno) );
- printf("msgrcv failed, rc=%d\n", rc);
- return 1;
- }
- printf("received msg: %s\n", msg.mtext);
- printf("received len: %d\n", msg.len);
- // remove the queue
- rc=msgctl(msgqid,IPC_RMID,NULL);
- if (rc < 0) {
- perror( strerror(errno) );
- printf("msgctl (return queue) failed, rc=%d\n", rc);
- return 1;
- }
- printf("message queue %d is gone\n",msgqid);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement