#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#define SHM_KEY 1234

using namespace std;

int main(int argc, char **argv){

	if (argc<2 || argc >3){
		cout<< "Usage: ./as2 N [delete]" << endl;
		return 1;
	}
	int n=atoi(argv[1]);
	bool deleteShm=false;
	if(argc==3 && strcmp(argv[2],"delete")==0){
		deleteShm=true;
	}
	int shmId=shmget(SHM_KEY,0,0666);
	if(shmId<0){
		cout << "memory does not exist!" <<endl;
		return 1;
	}
	cout << "Memory found with shmid=" <<shmId <<endl;
	int *matrix=(int *) shmat(shmId,NULL,0);
	//row major
	for(int row=0;row<n;row++){
		for(int col=0; col<n;col++){
			cout<<matrix[row*n+col]<<" ";
		}
		cout<<endl;
	}
	if (deleteShm) {
		shmctl(shmId,IPC_RMID,NULL);
		cout << "Memory deleted !" << endl;
	}
	return 0;
}

