Hi everybody, :o
I hope you can help me to solve this problem I have.
I'm trying to write a program with Linux in C which uses semaphores and shared memory. In particular I need to create a leader process and three more processes "calculators" (1, 2 and 3) that make mathematical operations. The leader process must create two numbers (x and y) and it has to choose randomly one of those operations. I've already written this part, you can find it below. The part I'm unable to write is the following. X and Y and the selected operation are given to the calculator processes. All of the calculator processes must wait the input from the leader process. When they know which is the operation, they give the result to the leader process. I have to implement this part by using semaphores and shared memory (without message queues). Could you help me with this?
I'd appreciate it a lot. Thank you very much!
This is my (incomplete) code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
int waitSem(int semid) {
struct sembuf wait_buf;
wait_buf.sem_num = 0;
wait_buf.sem_op = -1;
wait_buf.sem_flg = SEM_UNDO;
if(semop(semid, &wait_buf, 1) == -1) {
perror("waitSem failed");
exit(1);
}
return(0);
}
<code>int signalSem(int semid) {
<code>struct sembuf signal_buf;
signal_buf.sem_num = 0;
signal_buf.sem_op = 1;
signal_buf.sem_flg = SEM_UNDO;
if(semop(semid, &signal_buf, 1) == -1) {
perror("signalSem failed");
exit(1);
}
return(0);
}
int main(){
int x[9];
int y[9];
int op[9];
int n = 10;
int i;
long int res[9];
char *oper[9];
key_t
ftok(const char *pathname, int proj_id);
key_t mykey;
mykey = ftok("/", 80);
int smget(mykey, 2, 2);
srand(time(NULL));
for(i=0;i<n;i++){
x = rand() % 11;
y = rand() % 11;
op = rand() % 3;
switch(op){
case 0:
oper = "+";
res=x+y;
break;
case 1:
oper = "*";
res=x*y;
break;
case 2:
oper = "^";
ris=pow(x,y);
break;
}
}