Question
Write a program that tests the existence of a lock on a file. Use the program writelock- afile.c to lock a file. When there is
Write a program that tests the existence of a lock on a file. Use the program writelock-
afile.c to lock a file. When there is a lock on a file, your program (testlock.c) should print the ID of the process holding the lock. Otherwise, it prints the message File is not locked.
C language under Linux
For example, in one window do: $ touch test-file $ ./writelockafile test-file my pid is 5166 locking locked; hit enter to unlock... In another window, run: $ ./testlock test-file File is locked by 5166 When the file is not locked, you should get: $ ./testlock test-file File is not locked For a non-existent file, you should get: ./testlock non-existent-file *** No such file or directory
*******************************************************
writelockafile.c:
#include #include #include #include
/* Creates a write lock on a file */ int main (int argc, char* argv[]) { char* file = argv[1]; int fd; struct flock lock;
printf ("my pid is %d ", (int) getpid ());
printf ("opening %s ", file); /* Open a file descriptor to the file */ fd = open (file, O_WRONLY); printf ("locking "); /* Initialize the flock structure */ memset (&lock, 0, sizeof(lock)); lock.l_type = F_WRLCK; /* Place a write lock on the file */ fcntl (fd, F_SETLKW, &lock);
printf ("locked; hit enter to unlock... "); /* Wait for the user to hit enter */ getchar ();
printf ("unlocking "); /* Release the lock */ lock.l_type = F_UNLCK; fcntl (fd, F_SETLKW, &lock);
close (fd); return 0; }
*******************************************************
Makefile:
all: writelockafile.o cc -o writelockafile writelockafile.o
writelockafile.o: writelockafile.c cc -c writelockafile.c
clean: rm -f *.o writelockafile
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started