1. #include #include #include /* define key */ int key=2709; /* message */ char *messu[] = { "Hello", "Countdown", "5", "4","3","1","sorry, 2","1","GO\007", "------------------------------" }; /* number of fields in message */ int n=10; char *shmat(); main() { int id,i; char *seg; /* transform key to identifier of the shared segment */ /* key = 2709, size of the segment is 1024 bytes, create with */ /* permissions 0777 */ /* IPC = InterProcess Communication */ /* see man shmget, man shmat */ id = shmget(key,1024,IPC_CREAT | 0777); if (id == -1) {perror("shmget"); exit(1);} /* place shared segment to memory and return it's address seg */ /* (char *) 0 means that OS will decide the location for a shared memory */ seg = shmat(id,(char *)0,0); /* write into shared memory, sleep 1 second */ for(i=0;;) { sprintf(seg,"%s",messu[i]); i++; i = i % n; sleep(1); } } 2. #include #include #include char *shmat(); /* key is 2709*/ int key=2709; main() { int id,i; char *seg; /* transform key to id of the shared segment */ /* key = 2709, size of the segment is 1024 bytes, create with */ /* readonly-permission */ id = shmget(key,1024, SHM_RDONLY); if (id == -1) {perror("shmget"); exit(1);} /* Locate seg to shared memory */ /* (char *)0 means that system will find the corresponding address */ seg = shmat(id,(char *)0,0); /* Read from shared memory, sleep 1 second */ while(1){ printf("%s\n",seg); sleep(1); } } 3. Program 1 writes a message in shared memory segment in every 1 second and program 2 reads and display the contents of the shared memory in every 1 second.