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 12:26 PM, Petr Baudis <pasky@suse.cz> wrote:
> POSIX semaphores is one way - if your system has linxu manpages, see
> sem_overview(7). Moreover, often it is even simpler to use purely
> file-based locks, it depends on what fits better the actions you
> perform in the critical section.
>
> Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ÂPetr "Pasky" Baudis
>

Hi,

I thought about file based locks and I did the following:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {

  struct flock fl;
  int fd;

  fl.l_type = F_WRLCK;
  fl.l_whence = SEEK_SET;
  fl.l_start = 0;
  fl.l_len = 0;
  fl.l_pid = getpid();

  fd = open("lock", O_WRONLY);
  fcntl(fd, F_SETLKW, &fl);

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

  fclose(fp);

  // ------- END LOCKED REGION -----------

  fl.l_type   = F_UNLCK;  /* tell it to unlock the region */
  fcntl(fd, F_SETLK, &fl); /* set the region to unlocked */

  return 0;

}


I expected the second process to wait in the fcntl call untill the
first process calls the unlock (at fcntl), however, this is not what
happens. both enter the critical region at the same time.

What's the best way to use file locking to avoid two processes in the
same code region?

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]