2

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);
  }
K.W.
  • 59
  • 1
  • 10

1 Answers1

2

The fork operation creates a separate address space for the child process which is an exact copy of the parent process. So, your variable i with the value 0 will be replicated into the child process you are spawning and has it's own separate existence, which is the reason why you see i value as 1 in both the prints.

Rodia
  • 1,407
  • 8
  • 22
  • 29
Jay
  • 24,173
  • 25
  • 93
  • 141
  • should I use the shared memory mechanism to store variable i? – K.W. Mar 02 '17 at 06:49
  • Yes, you should if you want to share the variable between parent and child process. Refer to http://stackoverflow.com/questions/13274786/how-to-share-memory-between-process-fork – Jay Mar 02 '17 at 06:53
  • I think your intention is to learn more about critical sections. Then that is more aligned with multi-threading (with like pthreads) not multi-processing (with like `fork()`). So I suggest to check out [pthreads](https://computing.llnl.gov/tutorials/pthreads/) – Arash Mar 02 '17 at 08:09