#include <iostream>
#include <cstdlib>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#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;
}

