0

I am trying to study fnctl record locking. I created two files file1.c and file2.c. Both files write a string to "data" file. I created a lock using fnctl for whole file. when I run both programs from two terminals (cc file1.c -o file1) (cc file2.c -o file2) first ./file1 from terminal one and then ./file2 from terminal 2, First file1 program writes "abcdefghijklmnop" to data file and file2 program waits because of the lock. After Unlocking lock of file1, file2 writes "ABCDEFGHIJKLMNOP" to data file. Can someone improve my code to set a lock for some bits (like 4 to 9) and that program should notify that lock is encountered?

file1.c

void main()
    {

            struct flock v;
            int fd,i;
            char s[]="abcdefghijklmnop";
            // char s[]="ABCDEFGHIJKLMNOP"; in file2.c

            fd = open("data",O_RDWR|O_CREAT|O_APPEND,0644);

            v.l_type = F_WRLCK;
            v.l_whence = SEEK_SET;
            v.l_start = 0;
            v.l_len = 0;

            printf("Before...\n");

            fcntl(fd,F_SETLKW,&v);

            printf("After....\n");

            for(i=0;s[i];i++)
            {
                    write(fd,&s[i],1);
                    sleep(1);
            }

            v.l_type = F_UNLCK;
            fcntl(fd,F_SETLK,&v);

            printf("Done...\n");

    }
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
Nazeem
  • 59
  • 11
  • Just play with `l_start` and `l_len` and F_GETLK`, or I don't understand your question? – Jean-Baptiste Yunès Jan 02 '17 at 18:51
  • Just want to lock few bytes in data file by file1.c program. How to check presence of lock in particular byte ? and when file2 tries to write in those bytes, some "lock present" message display. – Nazeem Jan 02 '17 at 19:24
  • I said `F_GETLK`. – Jean-Baptiste Yunès Jan 02 '17 at 19:35
  • If i set 1_start and 1_len to 5 and 5, output is same as previous. No change in data file. First file1 program writing and then file2 program writing – Nazeem Jan 02 '17 at 20:30
  • Because you opened the file with `O_APPEND`, every write will go after the current end of the file. Is that what you intended? – Mark Plotnick Jan 03 '17 at 02:19
  • No. Even if file1 program has lock on some bytes in data file, file 2 program is also writing in same file on those locked bytes at same time. how is this possible? – Nazeem Jan 03 '17 at 03:17
  • Locks are generally not mandatory, just advisory. So programs need to cooperate explicitly in some way (F_GETLK for example). Different systems use different tricks to let you set mandatory locking on files (Linux combines GID-bit set while EXE-bit off for example). – Jean-Baptiste Yunès Jan 03 '17 at 05:06

0 Answers0