how do you get the message from the message queue in get.c file, after sending message and process id from send.c?
from send.c:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COUNT 200
#define BUF_SIZE 100
#define MSGSZ 255
#define KEY 10
//from http://www.tldp.org/LDP/LG/issue89/misc/raghu/send.c.txt
/*
* Declare the message structure.
*/
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ + 1];
} message_buf;
static message_buf sbuf;
static size_t buf_length;
static int mqid;
int main(int argc, char*argv[])
{
pid_t pid;
int i;
char buf[BUF_SIZE];
if ((pid = getpid()) < 0) { //getting child process id
perror("unable to get pid \n");
}
else {
printf("The process id is %d \n", pid);
}
char line[256];
int c = 0; //for character count
printf("enter word/s (must be less than or equal 256 characters): \n");
fgets(line, 256, stdin);
printf("\n");
if ( c > 256 )
{
printf("Must enter less than or equal to 256 characters.");
printf("Has %d characters", countChar(line));
exit(0);
}
(void) strcpy(sbuf.mtext, line);
buf_length = strlen(sbuf.mtext) + 1;
sbuf.mtype = pid;
logMessage(sbuf.mtype, line);
}
int countChar(char *s)
{
int len = 0;
for(; *s != '\0'; s++, len++);
return len;
}
int logMessage(int serviceId,char*message)
{
int rv, mask, msgid;
key_t key = KEY;
mask = 0644|IPC_CREAT;
msgid = msgget(key, mask);
if (msgsnd(msgid, &sbuf, buf_length, IPC_NOWAIT) < 0) //sending message
{
perror("msgsnd");
exit(1);
}
else
{
printf("id - %d : message - %s \n", serviceId, message);
}
return rv;
}
from get.c:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define MSGSZ 255
#define MSGCHARS 255
#define KEY 10
typedef struct msgbuf
{
int mtype;
char mtext[MSGSZ];
}message_buf;
static int queue_id;
void INThandler(int);
int main(int argc, char*argv[])
{
key_t key = KEY
message_buf rbuf;
int msgflg = 0644;
int msqid = msgget(key, msgflg);
if (msqid < 0) {
perror("msgget");
exit(1);
}
rbuf.mtype = 1;
for(;;){
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
printf("id - %d : message - %s ", rbuf.mtype, rbuf.mtext);
}
signal(SIGINT, INThandler);//the function starts with ctrl+c.
while (1)
pause();
return 0;
}
void INThandler(int sig)//this function deletes the message queue
{
signal(sig, SIG_IGN);
int mask, msgid;
key_t key = KEY;
mask = 0644;
msgid = msgget(key, mask);
if (msgid == -1) {
printf("Message queue does not exist.\n");
exit(EXIT_SUCCESS);
}
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
fprintf(stderr, "Message queue could not be deleted.\n");
exit(EXIT_FAILURE);
}
else {
printf("Message queue was deleted.\n");
}
exit(0);
return EXIT_SUCCESS;
}
I was able to send the process id and message successfully from send.c, but when executing get.c the code returns nothing. How do you fix that?