Ospp-Tute-File Management
Ospp-Tute-File Management
Practice session
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
// Buffer to read file data
char buf[100];
// This specifies the offset of the start of the region to which the lock applies,
// and is given in bytes relative to the point specified by the l_whence member.
fl.l_start = 0;
// This specifies the length of the region to be locked. A value of 0 is treated
// specially; it means the region extends to the end of the file.
fl.l_len= 10;
printf("Locked\n");
close(fd);
return 0;
}
This program will write lock a sample.txt file. As it is write lock, when try
to execute the same program in another window, it wont lock. Only when
the first program (first window) releases lock, the second window will
apply lock
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char buf[100];
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len= 0;
fl.l_pid = getpid();
This program will read lock a sample.txt file. As it is read lock, when try to
execute the same program in another window, it will lock. This is because
two reader shall operate on file simultaneously
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char buf[100];
struct flock fl;
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len= 0;
fl.l_pid = getpid();
printf("Applying\nread lock");
int fd = open("sample.txt", O_RDONLY);
if (fd == -1)
{
perror("Unable to open file: ");
exit(EXIT_FAILURE);
}
int flag=read(fd,buf,100);
if(flag<0){
printf("Error occured while reading\n");
exit(1);
}
printf("Read file content:\n");
printf("%s\n",buf);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
//Create an variable of type struct flock to define the properties of locking
if(choice==2)
fl.l_type = F_RDLCK;
printf("Locked\n");
printf("Unlocked.\n");
return 0;
}
int
main(int argc, char *argv[])
{
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}