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


2009/12/31 Petr Baudis <pasky@suse.cz>:
> On Thu, Dec 31, 2009 at 02:09:28PM +0000, Paulo J. Matos wrote:
>> 2009/12/31 Petr Baudis <pasky@suse.cz>:
>> > But what's the problem? Why not simply
>> >
>> > Â Â Â Âint i = 0;
>> > Â Â Â Âchar buf[PATH_MAX];
>> > Â Â Â Âdo {
>> > Â Â Â Â Â Â Â Âsnprintf(buf, sizeof(buf), "run%d", ++i);
>> > Â Â Â Â} while (mkdir(buf, 0777) < 0 && errno == EEXIST);
>> >
>> > mkdir() should be atomic, so each process will always pick a different
>> > name.
>> >
>>
>> That's a good solution! Now, that I look into mkdir() though I can't
>> find any reference to it being atomic. Are you sure that's the case?
>
> That is good question; I think it should be the case on all sensible
> systems, but I'm not sure. It might be good to ask on the austin-group
> mailing list why is it not described as atomic in the POSIX spec.
>
> Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ÂPetr "Pasky" Baudis
>

I will confirm that, thanks. In the meantime, I tried the following
with sems but two processes still go into the critical region at the
same time:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>

int main(void) {


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

  sem_wait(s);

  // ------- 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);

  return 0;

}

Any tips?


-- 
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]