Hello I am working on a C program for an IPC, this is my assignment below: IPCs.
ID: 3677693 • Letter: H
Question
Hello I am working on a C program for an IPC, this is my assignment below: IPCs. In each case you are to write a server to initialize the IPC structure, and then fork a client (which you also write) to process the structure created. 1) Write a server and client for message queues. The server should enqueue several messages (the message data can be a string of characters), and the client should dequeue it and write the message data read to an output file. Please help me with this!! I will be posting part 2 as a seperate questioned linked below. Thank you!
https://www.chegg.com/homework-help/questions-and-answers/hello-working-two-part-ipc-program-need-help-writing-two-aspects-program-added-seperate-qu-q11265189
Explanation / Answer
sender.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 128
//error occured.. closing server
void dieError(char *msg)
{
perror(msg);
exit(1);
}
//storing message
struct messageBuffer
{
long msgType;
char message[MAXSIZE];
};
main()
{
//variables declared
int msgId;
int flag = IPC_CREAT | 0666;
key_t key;
struct messageBuffer buff;
size_t bufferLength;
key = 1234;
if ((msgId = msgget(key, flag )) < 0) //getting message for given ID
dieError("msgget");
//setting message type
buff.msgType = 1;
//reading message
printf("Enter meesage: ");
scanf("%[^ ]",buff.message);
getchar();
//getting buffer length
bufferLength = strlen(buff.message) + 1 ;
//sending message
if (msgsnd(msgId, &buff, bufferLength, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d ", msgId, buff.msgType, buff.message, bufferLength);
dieError("message send");
}
else
printf("Message as been Sent ");
exit(0);
}
----------------------------------------------------------------------------------------------------------------------------------------------
receiver.c file
---------------------------------------------------
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
//error occured.. closing server
void dieError(char *msg)
{
perror(msg);
exit(1);
}
//storing message
typedef struct messageBuffer
{
long msgType;
char message[MAXSIZE];
};
main()
{
//variables declared
int msgId;
key_t key;
struct messageBuffer receiverBuffer;
FILE *fileptr;
//setting key
key = 1234;
if ((msgId = msgget(key, 0666)) < 0)
die("message get()");
//opening file
fileptr=fopen("output.txt","w");
//receiving message
if (msgrcv(msgId, &receiverBuffer, MAXSIZE, 1, 0) < 0)
die("message receive");
//recieved message
printf("%s ", receiverBuffer.message);
//writing message to output file
fprintf(fileptr,"%s",receiverBuffer.message);
exit(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.