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 "se207_sems.h"
- /* Remember to try reversing the timings...*/
- int bufferlength = 8; //Limited buffer length
- //what could we do about this?
- int main(int argc, char argv[]){
- //Create shared memory segment
- int shm_id = shmget(ftok("prodcon_example2.c", 2), bufferlength,
- 0666 | IPC_CREAT);
- int shm_id2 = shmget(ftok("prodcon_example2.c", 3), 2,
- 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...
- char* location;
- int pid = fork();
- if (pid){
- //P1 - CONSUMER
- shm_id = shmget(ftok("prodcon_example2.c", 2), 0, 006);
- shm_id2 = shmget(ftok("prodcon_example2.c", 3), 0, 006);
- //Attach the shared buffer
- data = shmat(shm_id, (void *)0, 0);
- location = shmat(shm_id2, (void *)0, 0);
- while (1){
- while (location[0] = location[1]){
- }
- //printf("Consuming item number %d...\n", location[1]);
- printf("consuming");
- sleep(1);
- //char item = data[location[1]];
- //printf("Consumed item number %d. Item value was %d\n",
- //location[1], item);
- //location[1] = (location[1] + 1) % bufferlength;
- }
- }
- else{
- //P2
- shm_id = shmget(ftok("prodcon_example2.c", 2), 0, 006);
- shm_id2 = shmget(ftok("prodcon_example2.c", 3), 0, 006);
- //Attach the shared buffer
- data = shmat(shm_id, (void *)0, 0);
- location = shmat(shm_id2, (void *)0, 0);
- while(1){
- while ((location[0] + 1) % bufferlength == location[1]){
- }
- //printf("Producing item number %d...\n", location[0]);
- printf("Producing array size %d... value =%d consumer value =%d\n", sizeof(location),location[0], location[1]);
- sleep(2);
- //data[location[0]] = location[0] * 2; //Simple data, easy to check.
- //location[0] = (location[0] + 1) % bufferlength;
- //printf("Produced item number %d. Value is %d\n",
- //location[0], data[location[0]]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement