Write your own simple client/server set of processes in the C language.
The client should use a shared memory segment to send a command message to the server.
You may not use sockets or multithreading, as we have not gone over that yet in my class.
The server process should monitor the shared memory segment, and respond as follows:
“HI” — The server prints “Greetings” to the screen.
“PID” — The server prints it’s process id to the screen.
“QUIT” — The server terminates gracefully, detaching and releasing the shared memory segment.
**Note, please do not copy and paste a solution from here or Google. I am looking for a unique solution to help me better understand this assignment. Thank you.**
Hints :
Use polling (an intentional infinite loop) in the server to monitor the shared memory segment.
You will need some way to coordinate sharing the memory segment.
read man pages for shmdt, shmget, shmat, shmctl, semctl, semop, semget
Expert Answer
-
//Developed by parth patel #include <stdio.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/ipc.h> #include <string.h> #include <unistd.h> int main() { int shmgetid; char input[200]; char* shmatpt = NULL; shmgetid = shmget(100, 200, 0777); shmatpt = shmat(shmgetid, NULL, 0); while( 1 ) { printf("> "); fgets(input, 200, stdin); input[strlen(input)-1] = ' '; strcpy(shmatpt, input); if( strcmp(input, "QUIT")==0){ break; } } }
server.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <sys/shm.h> #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> #include <string.h> void handlecontrolC(int); int shmgetid, id=0; char* shmatpt = NULL; int main() { signal(SIGINT, handlecontrolC); shmgetid = shmget(100, 200, IPC_CREAT | IPC_EXCL | 0777); shmatpt = shmat(shmgetid, NULL, 0); while(1) { if(strcmp(shmatpt, "HI")==0) { printf("Greetings!n"); fflush(stdout); shmatpt[0] = ' '; } else if(strcmp(shmatpt, "PID")==0) { id = (int)getpid(); printf("Server pid: %in", id); fflush(stdout); shmatpt[0] = ' '; } else if(strcmp(shmatpt, "QUIT")==0){ shmctl(shmgetid, IPC_RMID, NULL); shmdt(shmatpt); printf("GOODBYE!n"); exit(0); } } } void handlecontrolC(int XYZ) { shmctl(shmgetid, IPC_RMID, NULL); shmdt(shmatpt); printf("GOODBYE!n"); exit(0); }