This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Semaphores in libc


On Thu, Dec 31, 2009 at 2:50 PM, Luciano Rocha <strange@nsk.no-ip.org> wrote:
> On Thu, Dec 31, 2009 at 02:25:07PM +0000, Paulo J. Matos wrote:
>> Â sem_t *s = sem_open("/cvsa_driver_sem", O_CREAT, O_RDWR, 1);
>
> Instead of O_RDWR, you should specify the permissions for the created
> file. Like 0600.
>
>> Â sem_wait(s);
>
> Don't forget to check if the wait was interrupted.
>
> With the change I mentioned, your program works fine in my computer. I
> didn't test without the change.
>

Hi Luciano,

Either I misunderstood your suggestions or the server I am running
this in is not behaving as it should:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <errno.h>

char SEM_NAME[] = "/cvsa_driver_sem";

int main(void) {


  sem_t *s = sem_open(SEM_NAME, O_CREAT, 0600, 1);
  if(s == SEM_FAILED) {
    fprintf(stderr, "Semaphore failed.\n");
    return 1;
  }

  if(sem_wait(s)) {
    if(errno == EINTR)
      fprintf(stderr, "Wait interrupted...");
    return 0;
  }
  // ------- LOCKED REGION --------------

  FILE* fp = fopen("output", "w+");
  bool p = false;

  if(fp)
    for(unsigned long i = 0; i < ULONG_MAX; ++i) {
      if(!p) {
	printf("Printing...\n");
	p = true;
      }
      fprintf(fp, "hello %lu\n", i);
    }
  else
    printf("Can't open file\n");

  printf("Closing...\n");
  fclose(fp);

  // ------- END LOCKED REGION -----------
  sem_post(s);

  sem_close(s);
  sem_unlink(SEM_NAME);
  return 0;

}


I compiled this file and I ran it under two Putty terminals. In both
of them, I see "Printing..." at the same time meaning they are both in
the critical region. :-/
Don't you see the same thing?

Cheers,

-- 
Paulo Jorge Matos - pocmatos at gmail.com
http://www.pmatos.net


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]