How to randomnly lock some bytes in file using fcntl()?

270 views Asked by At

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

    }
0

There are 0 answers