Need some help in modifying a program.
Respected sir,
I have a producer-consumer programs that uses two semaphores to to control the shared resoures. I want to modify these two programs in such a way that it uses only single semaphore. I need to use an integer instead of array in Union.
Here are the programs:
=================
PRODUCER
=================
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define PUB7645 "./PubFile"
union semun {
int val;
struct semid_ds *buf;
ushort *array;
};
int
main() {
int i=0, intValue, semID;
key_t key;
FILE *fptr;
union semun arg;
static ushort startVal[2] = {1, 0};
static struct sembuf acquire = {0, -1, SEM_UNDO},
release = {1, 1, SEM_UNDO};
key = ftok(".", 's');
if ((semID = semget(key, 2, IPC_CREAT | 0666)) == -1) {
perror("Sem Creation:");
exit(2);
}
arg.array = startVal;
if (semctl(semID, 2, SETALL, arg) == -1 ) {
perror("semctl: SETALL");
exit(3);
}
for( ; ; ) {
srand(getpid()+i);
intValue =rand()*49/RAND_MAX + 1;
if (semop(semID, &acquire, 1) == -1) {
perror("Producer waiting");
exit(4);
}
if ((fptr = fopen(PUB7645, "w")) == NULL) {
perror(PUB7645);
exit(1);
}
fprintf(fptr, "%d\n", intValue);
fclose(fptr);
if (semop(semID, &release, 1) == -1) {
perror("new");
exit(5);
}
i++;
}
}
=================
Consumer:
=================
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define PUB7645 "./PubFile"
union semun {
int val;
struct semid_ds *buf;
ushort *array;
};
int main() {
int i=0, intValue, semID;
key_t key;
FILE *fptr;
union semun arg;
static struct sembuf acquire = {1, -1, SEM_UNDO},
release = {0, 1, SEM_UNDO};
key = ftok(".", 's');
if ((semID = semget(key, 2, IPC_CREAT | 0666)) == -1) {
perror("Sem Creation:");
exit(2);
}
for(i=1; i<=5 ; i++) {
if (semop(semID, &acquire, 1) == -1) {
perror(“Consumer waiting");
exit(4);
}
if ((fptr = fopen(PUB7645, "r")) == NULL) {
perror(PUB7645);
exit(1);
}
fscanf(fptr, "%d", &intValue);
fclose(fptr);
if (semop(semID, &release, 1) == -1) {
perror(“Release");
exit(4);
}
printf("%d\t", intValue);
}
printf("\nI am process %d. I got five numbers ", getpid());
printf("from a producer as above.\n");
}
Thanks.
|