SlideShare a Scribd company logo
UNIX SYSTEMS PROGRAMMING
AND COMPILER DESIGN
LABORATORY
3. Consider the last 100 bytes as a
region. Write a C/C++ program to
check whether the region is locked or
not. If the region is locked, print pid of
the process which has locked. If the
region is not locked, lock the region
with an exclusive lock, read the last 50
bytes and unlock the region.
• Objective : demonstrate lock unlock
mechanisms on record in a file.
• Last 100 bytes are to be locked
• If already locked then the Process ID which
has locked the file has to be printed
• Else the region has to be locked and last 50
bytes read and then unlock the region
• Advisory locking
• Mandatory locking
• Shared locks
• Exclusive lock
• File locking
• Record locking
• lock promotion
• lock splitting
Compatibility rules:
• File locking locks an entire file
• Record locking allows a process to lock a
specific portion of a file
• fcntl API for file locking
#include < fcntl.h >
int fcntl ( int fdesc , int cmd_flag , . . . );
• fdesc is a file descriptor for a file to be
processed
• cmd_flag values
cmd_flag Use
F_SETLK Sets a file lock. Do not block if this
cannot succeed immediately
F_SETLKW Sets a file lock and blocks the
calling process until the lock is
acquired
F_GETLK Queries as to which process locked
a specified region of a file
• For file locking, the third argument to fcntl is an address of a struct
flock
struct flock
{
short l_type; //what lock to be set or to unlock file
short l_whence; //a reference address for the next filed
off_t l_start; //offset from the l_whence reference address
off_t l_len; //how many bytes in the locked region
pid_t l_pid; // PID of a process which has locked the file
}
• The l_type filed specifies the lock type to be
set or unset.
l_type value Use
F_RDLCK Sets a read (shared) lock
on a specified region
F_WRLCK Sets a write (exclusive
lock on a specified region)
F_UNLCK Unlocks a specified region
• The possible values of l_whence and their
uses:
l_whence value Use
SEEK_CUR The l_start value is added to
the current file pointer
address
SEEK_SET The l_start value is added to
byte 0 of the file
SEEK_END The l_start value is added to
the end (current size) of the
file
• The l_len cannot have a negative value.
• The default lock set by the fcntl is an advisory
lock.
• The child process created through fork will
not inherit the file lock.
• lock promotion
• lock splitting
open API
• To open a file and establish a connection between a process
and a file
Function prototype
#include <sys/types.h>
#include <fcntl.h>
int open( const char *path_name, int access_mode , mode_t
permission);
• First argument path_name : path name , may be absolute or
relative
• Second argument access_mode: specifies how the file is to be
accessed by calling process , and defined in <fcntl.h> header
Access mode flag Use
O_RDONLY Open the file for read only
O_WRONLY Open the file for write only
O_RDWR Open the file for read and write
lseek API
• To set the file descriptor to beginning of required record location lseek
API is used
• lseek allows a process to perform random access of data on any opened
file
Function Prototype:
#include<sys/types.h>
#include<unistd.h>
off_t lseek ( int fdesc , off_t pos , int whence ) ;
• First argument : fdesc is an integer file descriptor that refers to an
opened file
• Second argument : pos specifies byte offset to be added to a reference
location in deriving the new file offset value
• Third argument : whence gives reference location for pos
• The possible values of whence are :
whence value Reference location
SEEK_CUR Current file pointer
address
SEEK_SET The beginning of a file
SEEK_END The end of a file
read API
• To read content from file read API is used , which fetches a fixed size block of data
from a file referenced by a given file descriptor
Function prototype :
#include<sys/types.h>
#include<unistd.h>
ssize_t read( int fdesc , void * buf , size_t size );
• First argument : fdesc is an integer file descriptor that refers to an opened file.
• Second argument : buf is the address of a buffer holding any data read
• Third argument : size say how many bytes of data are to be read from the file.
• size_t is defined int the <sys/types.h> header
• Program layout
– Check if file descriptor can be obtained
– Set file descriptor to last 100th Byte
– Try obtaining Exclusive lock
– If locked print details of process which already has
acquired lock and exit
– Now set file descriptor to last 50th Byte
– Read and print content
– And again Set file descriptor to last 100th Byte and
unlock the region
Program:
#include<iostream>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
using namespace std;
int main( int argc , char *argv[] )
{
pid_t pid=fork();
struct flock fvar;
int fdesc;
char buf;
int rc;
off_t offset;
if ( pid == 0 )
{
//In child and printing Its and its parent process pid
cout << "n Parent process id : " << getppid()
<< "n Child Proicess id : " << getpid() << "n";
}
//Can file be opened in Read and Write mode
if ( ( fdesc = open ( argv[1] ,O_RDWR ) ) == -1 )
{
perror("open");
return(1);
}
//Set the file descriptor to last 100th byte in file
offset = lseek ( fdesc , -100 , SEEK_END );
if ( offset == -1 )
{
perror("lseek");
return(1);
}
fvar.l_type = F_WRLCK; //set a write exclusive lock
//on specified region
fvar.l_whence = SEEK_CUR;
fvar.l_start = 0; //start from SEEK_CUR current file
//descriptor location
fvar.l_len = 100; //lock 100 bytes from SEEK_CUR
if( fcntl( fdesc, F_SETLK , &fvar ) == -1 )
{
cout << "nFile has been lockedn";
if( pid == 0 )
{
cout <<"n Child process could not get lock , pid : "<<getpid();
cout << "n Child process does not inherit the lockn";
}
else if ( pid > 0 )
{
cout<<"n Parent process could not get lock , pid : "<<getpid();
}
// Set lock failed
//Checking which process has locked the file and what regions
while( fcntl(fdesc,F_GETLK,&fvar) != -1 && fvar.l_type != F_UNLCK )
{
cout<<"nFile : "<<argv[1]
<<" is locked by process with pid :"<<fvar.l_pid
<<" from "<<fvar.l_start<<" th byte in file"
<<" for "<<fvar.l_len<<" number of bytes , for "
<<(fvar.l_type == F_WRLCK ? "write" : "read" )
<<"nn";
if(!fvar.l_len)
break;
fvar.l_start +=fvar.l_len ;
fvar.l_len = 0;
}
//end of while for check of locks set by other processes
}// end of if check lock not possible
else
{
//Locking the file was successful , continue to read last 50 bytes
cout << "nnFile "<<argv[1]<<" was not locked "
<<"and acquring of Exclusive Lock was successfuln";
if ( pid == 0 )
{
cout <<"n Child process acquired the lock"
<<"n Child process pid : "<<getpid();
}
else
{
cout <<"n Parent process acquired the lock";
cout <<"n Parent process id :"<<getpid();
}
//Set the offset to last 50th byte
offset = lseek ( fdesc , -50 , SEEK_END );
if ( offset == -1 )
{
perror("lseek");
return(1);
}
//Read the content of file
cout<<"nnLast 50 bytes of file : "<<argv[1];
while( (rc = read( fdesc, &buf , 1 )) > 0 )
{
cout << buf;
}
//Again reset the file descriptor to last 100th byte
offset = lseek ( fdesc , -100 , SEEK_END );
fvar.l_type = F_UNLCK ; //unlocks a specific region
fvar.l_whence = SEEK_CUR;
fvar.l_start = 0;
fvar.l_len = 100;
sleep(5); //sleep for 5 seconds
//now unlock the locked region of file
if ( fcntl(fdesc,F_SETLKW,&fvar) == -1 )
{
perror("fcntl");
return(1);
}
cout << "nFile Unlocked successfullynn";
} // else file locking reading and unlocking successful
return 0;
}
Output:
$ cat file.txt
total 36
-rw-rw-r-- 1 rahul rahul 3484 Feb 26 12:47 2q
-rwxrwxr-x 1 rahul rahul 9931 Mar 2 10:51 a.out
-rw-rw-r-- 1 rahul rahul 297 Feb 25 12:46 charFile.txt
-rw-rw-r-- 1 rahul rahul 4007 Mar 2 10:51 excLock.cpp
-rw-rw-r-- 1 rahul rahul 3350 Feb 26 12:28 exclusiveLock.cpp
-rw-rw-rw- 1 rahul rahul 0 Mar 2 10:52 file.txt
-rw-rw-r-- 1 rahul rahul 809 Feb 25 13:48 printfromfile.cpp
-rwxrwxrwx 1 rahul rahul 227 Feb 25 11:57 textfile.txt
$ g++34 excLock.cpp
$ ./a.out file.txt
Parent process id : 18721
Child Proicess id : 18722
File file.txt was not locked and acquring of Exclusive Lock was successful
Child process acquired the lock
Child process pid : 18722
Last 50 bytes of file : file.txtxrwx 1 rahul rahul 227 Feb 25 11:57 textfile.txt
File has been locked
Parent process could not get lock , pid : 18721
File : file.txt is locked by process with pid :18722 from 345 th byte in file for 100 number of bytes , for write
File Unlocked successfully
Thank you

More Related Content

Similar to Unix System Programming and Compiler Design Laboratory 3.pptx

File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
DrJasmineBeulahG
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
vishnupriyapm4
 
files.pptx
files.pptxfiles.pptx
files.pptx
KeerthanaM738437
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
RutujaTandalwade
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
pavimalpani
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
YourHelper1
 
Linux basics
Linux basicsLinux basics
Linux basics
sirmanohar
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Perl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File ProcessingPerl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File Processing
Danairat Thanabodithammachari
 
File operations in c
File operations in cFile operations in c
MODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptxMODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptx
ManasaPJ1
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Prabhu Govind
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
Systems Programming - File IO
Systems Programming - File IOSystems Programming - File IO
Systems Programming - File IO
HelpWithAssignment.com
 
Read write program
Read write programRead write program
Read write program
AMI AMITO
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 

Similar to Unix System Programming and Compiler Design Laboratory 3.pptx (20)

File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Perl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File ProcessingPerl for System Automation - 01 Advanced File Processing
Perl for System Automation - 01 Advanced File Processing
 
File operations in c
File operations in cFile operations in c
File operations in c
 
MODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptxMODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptx
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
File management
File managementFile management
File management
 
Systems Programming - File IO
Systems Programming - File IOSystems Programming - File IO
Systems Programming - File IO
 
Read write program
Read write programRead write program
Read write program
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 

Recently uploaded

Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
riddhimaagrawal986
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
ramrag33
 

Recently uploaded (20)

Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
 

Unix System Programming and Compiler Design Laboratory 3.pptx

  • 1. UNIX SYSTEMS PROGRAMMING AND COMPILER DESIGN LABORATORY
  • 2. 3. Consider the last 100 bytes as a region. Write a C/C++ program to check whether the region is locked or not. If the region is locked, print pid of the process which has locked. If the region is not locked, lock the region with an exclusive lock, read the last 50 bytes and unlock the region.
  • 3. • Objective : demonstrate lock unlock mechanisms on record in a file. • Last 100 bytes are to be locked • If already locked then the Process ID which has locked the file has to be printed • Else the region has to be locked and last 50 bytes read and then unlock the region
  • 4. • Advisory locking • Mandatory locking • Shared locks • Exclusive lock • File locking • Record locking • lock promotion • lock splitting
  • 6. • File locking locks an entire file • Record locking allows a process to lock a specific portion of a file
  • 7. • fcntl API for file locking #include < fcntl.h > int fcntl ( int fdesc , int cmd_flag , . . . );
  • 8. • fdesc is a file descriptor for a file to be processed • cmd_flag values cmd_flag Use F_SETLK Sets a file lock. Do not block if this cannot succeed immediately F_SETLKW Sets a file lock and blocks the calling process until the lock is acquired F_GETLK Queries as to which process locked a specified region of a file
  • 9. • For file locking, the third argument to fcntl is an address of a struct flock struct flock { short l_type; //what lock to be set or to unlock file short l_whence; //a reference address for the next filed off_t l_start; //offset from the l_whence reference address off_t l_len; //how many bytes in the locked region pid_t l_pid; // PID of a process which has locked the file }
  • 10. • The l_type filed specifies the lock type to be set or unset. l_type value Use F_RDLCK Sets a read (shared) lock on a specified region F_WRLCK Sets a write (exclusive lock on a specified region) F_UNLCK Unlocks a specified region
  • 11. • The possible values of l_whence and their uses: l_whence value Use SEEK_CUR The l_start value is added to the current file pointer address SEEK_SET The l_start value is added to byte 0 of the file SEEK_END The l_start value is added to the end (current size) of the file
  • 12. • The l_len cannot have a negative value. • The default lock set by the fcntl is an advisory lock. • The child process created through fork will not inherit the file lock. • lock promotion • lock splitting
  • 13. open API • To open a file and establish a connection between a process and a file Function prototype #include <sys/types.h> #include <fcntl.h> int open( const char *path_name, int access_mode , mode_t permission); • First argument path_name : path name , may be absolute or relative • Second argument access_mode: specifies how the file is to be accessed by calling process , and defined in <fcntl.h> header
  • 14. Access mode flag Use O_RDONLY Open the file for read only O_WRONLY Open the file for write only O_RDWR Open the file for read and write
  • 15. lseek API • To set the file descriptor to beginning of required record location lseek API is used • lseek allows a process to perform random access of data on any opened file Function Prototype: #include<sys/types.h> #include<unistd.h> off_t lseek ( int fdesc , off_t pos , int whence ) ; • First argument : fdesc is an integer file descriptor that refers to an opened file • Second argument : pos specifies byte offset to be added to a reference location in deriving the new file offset value • Third argument : whence gives reference location for pos
  • 16. • The possible values of whence are : whence value Reference location SEEK_CUR Current file pointer address SEEK_SET The beginning of a file SEEK_END The end of a file
  • 17. read API • To read content from file read API is used , which fetches a fixed size block of data from a file referenced by a given file descriptor Function prototype : #include<sys/types.h> #include<unistd.h> ssize_t read( int fdesc , void * buf , size_t size ); • First argument : fdesc is an integer file descriptor that refers to an opened file. • Second argument : buf is the address of a buffer holding any data read • Third argument : size say how many bytes of data are to be read from the file. • size_t is defined int the <sys/types.h> header
  • 18. • Program layout – Check if file descriptor can be obtained – Set file descriptor to last 100th Byte – Try obtaining Exclusive lock – If locked print details of process which already has acquired lock and exit – Now set file descriptor to last 50th Byte – Read and print content – And again Set file descriptor to last 100th Byte and unlock the region
  • 19. Program: #include<iostream> #include<stdio.h> #include<sys/types.h> #include<fcntl.h> #include<unistd.h> using namespace std; int main( int argc , char *argv[] ) { pid_t pid=fork(); struct flock fvar; int fdesc; char buf; int rc; off_t offset; if ( pid == 0 ) { //In child and printing Its and its parent process pid cout << "n Parent process id : " << getppid() << "n Child Proicess id : " << getpid() << "n"; } //Can file be opened in Read and Write mode if ( ( fdesc = open ( argv[1] ,O_RDWR ) ) == -1 ) { perror("open"); return(1); }
  • 20. //Set the file descriptor to last 100th byte in file offset = lseek ( fdesc , -100 , SEEK_END ); if ( offset == -1 ) { perror("lseek"); return(1); } fvar.l_type = F_WRLCK; //set a write exclusive lock //on specified region fvar.l_whence = SEEK_CUR; fvar.l_start = 0; //start from SEEK_CUR current file //descriptor location fvar.l_len = 100; //lock 100 bytes from SEEK_CUR
  • 21. if( fcntl( fdesc, F_SETLK , &fvar ) == -1 ) { cout << "nFile has been lockedn"; if( pid == 0 ) { cout <<"n Child process could not get lock , pid : "<<getpid(); cout << "n Child process does not inherit the lockn"; } else if ( pid > 0 ) { cout<<"n Parent process could not get lock , pid : "<<getpid(); } // Set lock failed //Checking which process has locked the file and what regions while( fcntl(fdesc,F_GETLK,&fvar) != -1 && fvar.l_type != F_UNLCK ) { cout<<"nFile : "<<argv[1] <<" is locked by process with pid :"<<fvar.l_pid <<" from "<<fvar.l_start<<" th byte in file" <<" for "<<fvar.l_len<<" number of bytes , for " <<(fvar.l_type == F_WRLCK ? "write" : "read" ) <<"nn"; if(!fvar.l_len) break; fvar.l_start +=fvar.l_len ; fvar.l_len = 0; } //end of while for check of locks set by other processes }// end of if check lock not possible
  • 22. else { //Locking the file was successful , continue to read last 50 bytes cout << "nnFile "<<argv[1]<<" was not locked " <<"and acquring of Exclusive Lock was successfuln"; if ( pid == 0 ) { cout <<"n Child process acquired the lock" <<"n Child process pid : "<<getpid(); } else { cout <<"n Parent process acquired the lock"; cout <<"n Parent process id :"<<getpid(); } //Set the offset to last 50th byte offset = lseek ( fdesc , -50 , SEEK_END ); if ( offset == -1 ) { perror("lseek"); return(1); }
  • 23. //Read the content of file cout<<"nnLast 50 bytes of file : "<<argv[1]; while( (rc = read( fdesc, &buf , 1 )) > 0 ) { cout << buf; } //Again reset the file descriptor to last 100th byte offset = lseek ( fdesc , -100 , SEEK_END ); fvar.l_type = F_UNLCK ; //unlocks a specific region fvar.l_whence = SEEK_CUR; fvar.l_start = 0; fvar.l_len = 100; sleep(5); //sleep for 5 seconds //now unlock the locked region of file if ( fcntl(fdesc,F_SETLKW,&fvar) == -1 ) { perror("fcntl"); return(1); } cout << "nFile Unlocked successfullynn"; } // else file locking reading and unlocking successful return 0; }
  • 24. Output: $ cat file.txt total 36 -rw-rw-r-- 1 rahul rahul 3484 Feb 26 12:47 2q -rwxrwxr-x 1 rahul rahul 9931 Mar 2 10:51 a.out -rw-rw-r-- 1 rahul rahul 297 Feb 25 12:46 charFile.txt -rw-rw-r-- 1 rahul rahul 4007 Mar 2 10:51 excLock.cpp -rw-rw-r-- 1 rahul rahul 3350 Feb 26 12:28 exclusiveLock.cpp -rw-rw-rw- 1 rahul rahul 0 Mar 2 10:52 file.txt -rw-rw-r-- 1 rahul rahul 809 Feb 25 13:48 printfromfile.cpp -rwxrwxrwx 1 rahul rahul 227 Feb 25 11:57 textfile.txt $ g++34 excLock.cpp $ ./a.out file.txt Parent process id : 18721 Child Proicess id : 18722 File file.txt was not locked and acquring of Exclusive Lock was successful Child process acquired the lock Child process pid : 18722 Last 50 bytes of file : file.txtxrwx 1 rahul rahul 227 Feb 25 11:57 textfile.txt File has been locked Parent process could not get lock , pid : 18721 File : file.txt is locked by process with pid :18722 from 345 th byte in file for 100 number of bytes , for write File Unlocked successfully