user1550036
user1550036

Reputation: 221

file lock in unix system using c and fcntl

I'm trying to learn programming c in unix. So I read through Beejs Guide and tried to learn more about file locking.

So I just took some Code example from him and tried to read out if the file is locked or not but every time I do, I get errno 22 which stands for invalid argument. So I checked my code for invalid arguments but I was unable to find them. Is anyone able to help me?

My error occurs in this:

        if( fcntl(fd, F_GETLK, &fl2) < 0 ) {
            printf("Error occured!\n");
        }

The full code:

    /*
    ** lockdemo.c -- shows off your system's file locking.  Rated R.
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <unistd.h>

    int main(int argc, char *argv[])
    {
                        /* l_type   l_whence  l_start  l_len  l_pid   */
        struct flock fl = {F_WRLCK, SEEK_SET,   0,      0,     0 };
        struct flock fl2;
        int fd;

        fl.l_pid = getpid();

        if (argc > 1) 
            fl.l_type = F_RDLCK;

        if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
            perror("open");
            exit(1);
        }

        printf("Press <RETURN> to try to get lock: ");
        getchar();
        printf("Trying to get lock...");

        if (fcntl(fd, F_SETLKW, &fl) == -1) {
            perror("fcntl");
            exit(1);
        }

        printf("got lock\n");



        printf("Press <RETURN> to release lock: ");
        getchar();

        fl.l_type = F_UNLCK;  /* set to unlock same region */

        if (fcntl(fd, F_SETLK, &fl) == -1) {
            perror("fcntl");
            exit(1);
        }

        printf("Unlocked.\n");

        printf("Press <RETURN> to check lock: ");
        getchar();

        if( fcntl(fd, F_GETLK, &fl2) < 0 ) {
            printf("Error occured!\n");
        }
        else{
            if(fl2.l_type == F_UNLCK) {
                printf("no lock\n");
            }
            else{
                printf("file is locked\n");
                printf("Errno: %d\n", errno);
            }
        }
        close(fd);

        return 0;
    }

I just added fl2 and the part at the bottom.

Upvotes: 2

Views: 4618

Answers (1)

Martin R
Martin R

Reputation: 540105

fcntl(fd, F_GETLK, &fl2) gets the first lock that blocks the lock description in fl2, and overwrites fl2 with that information. (Compare fcntl - file control)

That means that you have to initialize fl2 to a valid struct flock before calling fcntl().

Upvotes: 1

Related Questions