void initiate(char ** argv){ int key2 = ftok("makefile",'e'); //creating if (strcmp(argv[1], "--create") == 0){ createsharedmem(key2); createsem(key2); createfile("story.txt"); printf("INITIATED\n"); } //removing else if (strcmp(argv[1], "--remove") == 0) { //remove the shared memory (we need to remove pointers to memories separately or else shared memory will not disappear) removesharedmem(key2); //remove the semaphore removesem(key2); //display the file if (filesize() >0){ int fd; fd = open("story.txt", O_RDWR | O_APPEND, 0644); write(fd, "\n",2); } //Display the full contents of the story execlp("cat","cat","story.txt",NULL); } else{ printf("INVALID INPUT: Please run control with either '--create' or '--remove'.\n");// } }
int main (int argc,char* argv[]) { //main ss int semid,shmid; char *shmaddr; char write_str[SHM_SIZE]; memset(write_str,SHM_SIZE,'\0'); if ((shmid = createshm(".",'m',SHM_SIZE)) == -1) { exit(-1); } if((shmaddr = shmat(shmid,(char*)0,0)) == (char*)-1) { cout << "shmat error" << endl; } if((semid =(createsem(".",'s',1,1)))==-1) { exit(-1); } while(1) { wait_sem(semid,0); sem_P(semid,0); cout << "writer:"<< "do something here" << endl; fgets(write_str,1024,stdin); int length = strlen(write_str); write_str[len]='\0'; strncpy(shmaddr,write_str,len+1); sleep(10); } return 0; }
int diningphilosopher() { status= shmat(shmid, (void *)0, 0); for(int i=0;i<N;i++) { createsem(i); } for(int i=0;i<N; i++) { // All the philosophers are thinking initially status[i]=THINKING; } for(int i=0;i<N;i++) { int a =fork(); if(a!=0) { // I am in the parent } else { down(i); philosopher(i); printf("status of philosopher %d = %d\n", i+1, status[i]); } } return 0; } // end of dining philosopher function