Hi,
I have added sleep with random timings and printed the values.

I am actually expecting the "Blocked in Child" OR "Blocked in Parent" out put when other process sleeps.
But it it never printing the statement.(when the process is going to sleep the semaphore is not cleared so i expect sem unavailable)

can some one please modify my program so that it is blocked atleast once in course of execution.

#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

int main(int argc, char **argv)
{
  int fd, i,count=0,nloop=10,zero=0,*ptr;
  sem_t mutex;

  //open a file and map it into memory

  fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
  write(fd,&zero,sizeof(int));
  ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
  close(fd);

  /* create, initialize semaphore */
  if( sem_init(&mutex,1,1) < 0)
    {
      perror("semaphore initilization");
      exit(0);
    }
  if (fork() == 0) { /* child process*/
   if ( -1 != sem_wait(&mutex) ) {
       for (i = 0; i < nloop; i++) {
          printf("child: %d\n", (*ptr)++);sleep(10);
             sem_post(&mutex);
          }

    }
    else {
             printf("Blocked in Parent\n");
    }
    exit(0);
  }
  /* back to parent process */
    if ( -1 != sem_wait(&mutex)) {
    for (i = 0; i < nloop; i++) {
        printf("parent: %d\n", (*ptr)++);sleep(5);
        sem_post(&mutex);
    }

    }   else {
        printf("Blocked in Child");
    }

  exit(0);
}

Thanks,
Gaiety.

sem_wait blocks execution for potentially an infinite amount of time if the semaphore value is already 0 in order to lock the semaphore. It only returns -1 if there is an error, including a signal, during the wait.

So "Blocked in Parent" and "Blocked in Child" will never be output. You could try calling sem_trywait which will return immediately if the semaphore can not be locked with a value of -1 and set errno to the value EAGAIN.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.