I've got a homework from operation systems. I have to write a code in what we have to use semafors. There is a father process in what we have to read 2 Int from a text file and with shared memory have to write onto standard output with the first child the first and with the second child the second number. My file name is "be.txt" and contains six numbers 1 3 1 4 1 5
I have rewrited my code, change the down and up structs values, but nothing changed. I got everytime as result 1 1 3 4 ... and here the program is just stuck and wait.
Ps.: myinclude.h is my header in what I've define the syserr funtcion and the library I needed it for the code.
#include "myinclude.h"
void fiufeladat(int semid, int * ip, short sem){
struct sembuf down = {sem, -1, 0};
struct sembuf up = {0, +1, 0};
int n;
while(1){
if(semop(semid, &down, 1)<0){
syserr("semop fiu feladat");
}
n = *ip;
if(semop(semid, &up, 1)<0) syserr("semop fiu feladat");
if(n == 0) break;
printf("%d ", n);
}
shmdt((void*)ip);
}
int main(){
int semid, shmid;
int * ip;
int init[]={2,0,0};
int n,m;
pid_t fiu1, fiu2;
struct sembuf down0 = {0, -2, 0};
struct sembuf up[] = {{1, +1, 0}, {2, +1, 0}};
setbuf(stdout, NULL);
if((semid = semget(ftok(".", 'a'), 3, IPC_CREAT | 0660 )) < 0) syserr("semget");
if((shmid = shmget(ftok(".", 'a'), 2*sizeof(int), IPC_CREAT| 0660))<0) syserr("shmget");
if(semctl(semid, 0, SETALL, init)<0) syserr("semctl");
ip = (int*)shmat(shmid, 0, 0);
if(ip == (void*)-1) syserr("shmat");
FILE * fp = fopen("be.txt", "r");
if(!fp) syserr("fopen");
if((fiu1 = fork()) < 0) syserr("fork fiu1");
if(fiu1 == 0){
fiufeladat(semid, ip, 1);
exit(0);
}
if((fiu2 = fork())<0) syserr("fork fiu2");
if(fiu2 == 0){
fiufeladat(semid, ip+1, 2);
exit(0);
}
while(1){
if(fscanf(fp, "%d %d", &n, &m) == EOF) {
*ip = 0;
*(ip+1) = 0;
}
if(semop(semid, &down0, 1) < 0) syserr("semop apa down0");
*ip = n;
*(ip+1) = m;
//printf("%d %d", n,m);
if(semop(semid, up, 2)<0){
syserr("semop apa fel");
}
if(*ip == 0 && *(ip+1) == 0) break;
}
semctl(semid, 0, IPC_RMID, 0);
shmdt((void*)ip);
shmctl(shmid, IPC_RMID, 0);
fclose(fp);
exit(0);
}