Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C program that sends messages from the child process to its parent. The

ID: 3765888 • Letter: W

Question

Write a C program that sends messages from the child process to its parent. The message will be entered by the user and then sent from the child process to the parent one using IPC. The message has a specific format. If the user entered his message starting with "exec: {cmd}", it means the parent will execute the entered command (i.e., ls, pwd, whoami, etc.). If the message is in the format "sleep: {n}", it means the child process will sleep for n seconds. You will need to define a constant, #define SIZE 1024, which specifies the maximum length of the message

Explanation / Answer

Answer :

Sender Code

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 128

void end(char *s)
{
perror(s);
exit(1);
}

struct msgbuffer
{
long mtype;
char mtext[MAXSIZE];
};

main()
{
int msgid;
int msgflag = IPC_CREAT | 0666;
key_t key;
struct msgbuffer sbuf;
size_t bufferlength;

key = 1234;

if ((msgid = msgget(key, msgflag )) < 0)   
end("msgget");

  
sbuf.mtype = 1;

printf("Enter a message to add to message queue : ");
scanf("%[^ ]",sbuf.mtext);
getchar();

bufferlength = strlen(sbuf.mtext) + 1 ;

if (msgsnd(msgid, &sbuf, bufferlength, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d ", msgid, sbuf.mtype, sbuf.mtext, bufferlength);
end("msgsnd");
}

else
printf("Message Sent ");

exit(0);
}

Receiver's Code :

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1024

void end(char *s)
{
perror(s);
exit(1);
}

typedef struct msgbuffer
{
long mtype;
char mtext[MAXSIZE];
} ;


main()
{
int msgid;
key_t key;
struct msgbuffer rcvbuffer;

key = 1234;

if ((msgid = msgget(key, 0666)) < 0)
end("msgget()");



if (msgrcv(msgid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
end("msgrcv");

printf("%s ", rcvbuffer.mtext);
exit(0);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote