user11432153
user11432153

Reputation:

Use of sem_wait in a program

I wrote this simple program that creates a child process and prints some messages inside:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
sem_t *init;


int main()
{
init=sem_open("/mysem", O_CREAT, 0644, 1);
pid_t c,c2;
c=fork();
if(c==0){
sem_wait(init);
for(int i=0;i<5;i++){
printf("critical1 \n");
}
}}

I read that sem_wait checks the value of the semaphore and if it is greater than 0 decrements it and proceed and if it is 0 it get's stuck there until this value is increased.So after initializing semaphore's value to 1 i expect sem_wait to continue normally and not block the program.However,in this case this program prints nothing and terminates(not just pause).What am i missing?

Upvotes: 1

Views: 363

Answers (1)

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19054

The problem here is that posix semaphores are persistent across program runs. The first time you run, it works. Subsequent runs the initialization value is ignored since the semaphore already exists and is therefore maintaining a value of zero. Try this modification which unlinks the semaphore when the program ends. Note that it might not work the first time you run it since the semaphore might exist on your computer. It will work on subsequent executions:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
sem_t *init;


int main()
{
  init=sem_open("/mysem", O_CREAT, 0644, 1);
  pid_t c,c2;
  c=fork();

  if(c==0)
  {
    printf("before sem_wait()\n");
    sem_wait(init);
    printf("after sem_wait()\n");

    for(int i=0;i<5;i++)
    {
      printf("critical1 \n");
    }
    sem_close(init);
  }
  else
  {
    sleep(5);
    printf("main() exiting.\n");
    sem_close(init);
    sem_unlink("/mysem");
  }
}

Upvotes: 2

Related Questions