Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include "se207_sems.h"
- #include <sys/wait.h>
- /* Remember to try reversing the timings...*/
- int bufferlength=8; //Length of buffer.
- int main(int argc, char argv[]){
- pid_t pid;
- int status = 0;
- int i;
- //Create shared memory segment
- int shm_id=shmget(ftok("prodcon_example2.c",2),bufferlength,
- 0666|IPC_CREAT);
- //Use our source file as the "key"
- int id=se207_semget("prodcon_example2.c",0);
- char* data; //For our pointer to shared memory...
- pid=fork();
- if(pid){
- //P1 - CONSUMER
- shm_id=shmget(ftok("prodcon_example2.c",2),0,006);
- //Attach the shared buffer
- data = shmat(shm_id, (void *)0, 0);
- int consumed=0;
- while(consumed<bufferlength){
- se207_wait(id);
- printf("Consuming item number %d...\n",consumed);
- sleep(1);
- char item=data[consumed];
- printf("Consumed item number %d. Item value was %d\n",
- consumed,item);
- consumed++; //Each time the while loop runs the consumer counter is incremented.
- if(consumed == 7) //If statement that checks to make sure that value of consumed is not greater than the value of the buffer length and sets it to 0 if the value is 7 effectively creating an infinite loop.
- {
- consumed = 0;
- }
- }
- //Detatch
- shmdt(data);
- printf("All done consuming.\n");
- wait(&status); //For child process so that we can
- //Delete the shared memory
- printf("Child ended, removing shm\n");
- shmctl(shm_id, IPC_RMID, NULL);
- }else{
- //P2 - PRODUCER
- shm_id=shmget(ftok("prodcon_example2.c",2),0,006);
- //Attach the shared buffer
- data = shmat(shm_id, (void *)0, 0);
- int produced=0;
- while(produced<bufferlength){
- printf("Producing item number %d...\n",produced);
- sleep(2);
- data[produced]=produced*2; //Simple data, easy to check.
- printf("Produced item number %d. Value is %d\n",
- produced,data[produced]);
- se207_signal(id);
- produced++;
- if(produced == 7) //If statement that checks to make sure that the value of produced is not greater than the value of the buffer length and sets it to 0 if the value is 7 effectively creating an infinite loop.
- {
- produced = 0;
- }
- }
- //Detatch
- shmdt(data);
- printf("Producer finished.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement