OS 9 New
OS 9 New
Experiment 1
In this assignment, you will implement a chat bot using shared memory in Linux. The chat
bot should communicate with the user using the shared memory segment and respond to the
user's messages based on the pre-defined rules.
Discussion & Sharedmemory.cpp:-(im using c libraries only i just renamed to cpp incase i
Output: would have to do file operations)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_KEY 1234
#define SHM_SIZE 1024
struct Msg {
int isUserMsg;
char text[256];
};
int main() {
int shmid;
void *shm = (void *)0;
struct Msg *msg;
int msgFlag = 0;
while(1) {
if (msg->isUserMsg == 1) {
if (strcmp(msg->text, "Hi") == 0) {
strcpy(msg->text, "Hello, how can I help you today?");
} else {
strcpy(msg->text, "Sorry, I didn't understand that.");
}
msg->isUserMsg = 0;
msgFlag = 1;
}
if (msgFlag == 1) {
printf("Bot: %s\n", msg->text);
msgFlag = 0;
sleep(1);
}
}
if (shmdt(shm) == -1) {
perror("shmdt failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
user .cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
// message structure
struct Message {
int isUserMessage;
char text[256]; //Max length of the message
};
int main() {
int shmid;
void *shared_memory = (void *)0;
struct Message *message;
while(1) {
// user give input
printf("User: ");
fgets(message->text, sizeof(message->text), stdin);
while (message->isUserMessage == 1) {
sleep(1); // Wait
}
if (shmdt(shared_memory) == -1) {
perror("shmdt failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
struct Message {
int isUserMessage;
char text[256];
};
int main() {
int shmid;
void *shared_memory = (void *)0;
struct Message *message;
shmid = shmget((key_t)SHARED_MEMORY_KEY,
SHARED_MEMORY_SIZE, 0666);
if (shmid == -1) {
perror("shmget failed");
exit(EXIT_FAILURE);
}
while(1) {
printf("User: ");
fgets(message->text, sizeof(message->text), stdin);
message->isUserMessage = 1;
while (message->isUserMessage == 1) {
sleep(1);
}
if (shmdt(shared_memory) == -1) {
perror("shmdt failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
CONCLUSION: Shared Memory implemented in linux .