I'm trying to make two processes modify a common variable while mutually excluding one another. The output I expect form this piece of code is
1 2 or 2 1
but I keep getting 1 1.
I've tried putting processes to sleep before entering the critical section but they're always performing all steps at the same pace and enter the critical section together. How can I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
static struct sembuf buf;
void enter(int semid, int semnum){
buf.sem_num = semnum;
buf.sem_op = 1;
buf.sem_flg = 0;
if (semop(semid, &buf, 1) == -1){
perror("Opening semaphore");
exit(1);
}
}
void leave(int semid, int semnum){
buf.sem_num = semnum;
buf.sem_op = -1;
buf.sem_flg = 0;
if (semop(semid, &buf, 1) == -1){
perror("Closing semaphore");
exit(1);
}
}
int main(int argc, char* argv[]){
int semid;
int i=0;
semid = semget(45281, 1, IPC_CREAT|0600);
if (semid == -1){
perror("Creating array of sems");
exit(1);
}
if (semctl(semid, 0, SETVAL, (int)1) == -1){
perror("Setting value to 1");
exit(1);
}
fork();
enter(semid,0);
i++;
leave(semid, 0);
printf("%d\n",i);
}