#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
using namespace std;

int main(){
	cout<<"========================================"<<endl;
	cout<<"    LINUX IPC: SHARED MEMORY SEGMENT    "<<endl;
	cout<<"========================================\n"<<endl;
	int shm_id=shmget(IPC_PRIVATE, 1024, 0666 | IPC_CREAT);
	if(shm_id<0){
		cerr<<"FATAL ERROR: Failed to allocate shared memory!"<<endl;
		return 1;
	}
	cout<<"[SYSTEM] Shared Memory allocated. ID: "<<shm_id<<endl;
	pid_t process_id=fork();
	if(process_id<0){
		cerr<<"FATAL ERROR: fork() failed!"<<endl;
		return 1;
	}
	else if(process_id==0){
		char* shared_whiteboard=(char*) shmat(shm_id, NULL, 0);
		cout<<"  ->[CHILD] I am int he shared room."<<endl;
		cout<<"  ->[CHILD] Writing data to the whiteboard..."<<endl;
		const char* secret_data="ACCESS GRANTED: The kernel barrier has been bypassed!";
		strcpy(shared_whiteboard, secret_data);
		shmdt(shared_whiteboard);
		cout<<"  ->[CHILD] Data written. Terminating."<<endl;
		return 0;
	}
	else{
		cout<<"[PARENT] Waiting for the child to write to memory..."<<endl;
		wait(NULL);
		char* shared_whiteboard=(char*) shmat(shm_id, NULL, 0);
		cout<<"[PARENT] The child is done. Let's look at the whiteboard:"<<endl;
		cout<<"[PARENT] MESSAGE READ: \""<<shared_whiteboard<<"\""<<endl;
		shmdt(shared_whiteboard);
		shmctl(shm_id, IPC_RMID, NULL);
		cout<<"[PARENT] Shared memory destroyed. Shutting down safely."<<endl;
	}
	return 0;
}
