First, I'd like to thank a lot to Glynn for the useful hints....

For the ones that are like me trying to lock local files, this works with me:

#include <stdio.h>
#include <unistd.h>     
#include <sys/types.h>  
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>      
#define YES 1
#define NO 0
#define TIMES 100000
#define TEXT "Prog1\n"

main (void)
{
  int fd;
  long int i;
  char *str2w=TEXT;
  int done;
  int flags_create=O_WRONLY | O_EXCL | O_CREAT;
  int flags_open=O_WRONLY | O_EXCL;
  int flags;


  done=NO;

  printf("Start.\n");
  flags=flags_open;
  while (!done) {
    printf("Attempt Opening.\n");
    fd = open("TEST", flags, 0777);
    printf("FD=%d\n",fd);
    if (fd > 0) {
       if (flock(fd, LOCK_EX) < 0) {
          /* this should not happen */
          printf("Not locked, will close the file and do open again.\n");
          close(fd);
       } else {
          printf("Writing to LOCKED! file\n");
          printf("Jump to the end.\n");
          lseek(fd,0L,SEEK_END);
          for(i=0; i<TIMES; i++)
            write(fd,str2w,strlen(str2w));
          close(fd);
          done=YES;
          printf("Done.\n");
       }
    } else {
      printf("Errno=%d\n",errno);
      if (errno==ENOENT) {
        flags=flags_create;
        printf("File doesnot exist, attempt to create in the next turn.\n");
      }
      else {
        flags=flags_open;
        printf("File already exist but could not open it, might be
locked.\n");
        sleep(1);
      }
    }
  }
}

This was prog1.c, I made also prog2.c with TEXT "Prog2\n" and attempt to
run them concurently from 2 consoles.... and examine TEST file...

Just one small question... Do I need to flock() even if it is O_EXCL ?

Regards and thanks,
Ljubisa Gavrilovic <[EMAIL PROTECTED]>

Reply via email to