Unit 2 Slides
Unit 2 Slides
Version 1.0
UNIX FILES
▪ Files are building blocks in an operating system
Version 1.0
File Types
File Types
Character Soft
Block Hard
Version 1.0
FILE TYPES
▪ Regular file
▪ Directory file
▪ Fifo file
▪ Character device file
▪ Block device file
▪ Link file
▪ Socket file
Version 1.0
Regular file
▪ Both the files are executable provided execution rights are set
Version 1.0
Directory file
Version 1.0
Device Files
▪ Two types
1. Block device file
▪ Physical device which transmits data a block at a time
EX: hard disk drive, floppy disk drive
Version 1.0
Device Files
▪ A physical device can have both character and block device file
Version 1.0
FIFO file
▪ Special pipe device file which provides a temporary buffer for two or
more processes to communicate by writing data to and reading data
from the buffer.
▪ The buffer associated with a FIFO file is allocated when the first
process opens the FIFO file for read or write
▪ The buffer is discarded when all the processes referencing the FIFO
close their reference .hence the data storage is temporary
▪ The file exists as long as there is one process which has a direct
connection to the FIFO file for data access
Version 1.0
FIFO file
mknod /usr/prog/fifo_pipe p
Version 1.0
Symbolic link file
cat -n /usr/ravi/slink
/*will print contents of /usr/satish/original file*/
Version 1.0
UNIX and POSIX file systems
Version 1.0
Common UNIX files
Version 1.0
UNIX and POSIX file attributes
Version 1.0
UNIX and POSIX file attributes
▪ File attributes are assigned by the kernel when the file is crated
Version 1.0
Attributes of a file that remain unchanged
▪ File type
▪ File inode number
▪ File system ID
▪ Major and minor device number
Version 1.0
File attributes that are changed using UNIX commands or system
calls
Version 1.0
File attributes that are changed using UNIX commands or system
calls
Version 1.0
Inodes in UNIX system
▪ UNIX system V has an inode table which keeps track of all files
▪ Each entry in inode table is an inode record
▪ Inode record contains all attributes of file including inode number
and physical disk address where the data of the file stored
▪ Information of a file is accessed using its inode number.
▪ Inode number is unique within a file system
▪ A file is identified by a file system ID and inode number
▪ Inode record does not contain the name of the file
▪ The mapping of filenames to inode number is done via directory files
Version 1.0
mapping of filenames to inode number
65 ..
95 abc
234 a.out
Version 1.0
Application Program Interface to Files
Version 1.0
Struct stat data type<sys/stat.h>
▪ Struct stat
{ dev_ts st_dev; /* file system ID */
ino_t st_ino; /* File inode number */
mode_t st_mode; /* file type and access flags */
nlink_t st_nlink; /*Hard link count */
uid_t st_uid; /* File user ID */
gid_t st_gid; /* File group ID */
dev_t st_rdev; /* Major and Minor device numbers */
off_t st_size; /*File size in number of bytes */
time_t st_atime; /* Last access time */
time_t st_mtime; /* last modofication time */
time_t st_ctime /* Last status change time */
};
Version 1.0
UNIX KERNEL SUPPORT FOR FILES
▪ Each process has its own data structures: file descriptor table is one
among them.
▪ File descriptor table has OPEN_MAX entries, and it records all files
opened by the process.
Version 1.0
Kernel support to open system call
1. The kernel will search the file descriptor table and look for first
unused entry and index to the entry is returned as file descriptor of
the opened file.
2. The kernel will scan the file table in its kernel space , to find an
unused entry that can be assigned to reference the file
3. If an unused entry is found in the file table,then the following
events will occur:
Version 1.0
Kernel support to open system call
b. The file table entry will be set to point to inode table entry
where the inode record of file is present.
c. The file table entry will contain the current file pointer of the
open file.
d. The file table entry will contain an open mode which specifies
the file is opened for read- only ,write-only etc,.
Version 1.0
Data Structure for File Manipulation
rw
rc=1 rc=2
w
rc=1
Version 1.0
Data Structure for File Manipulation
Inode
2 Status flags
Information
O_CREAT,O_EXCL,
3 ptr O_TRUNC,O_APPEN Reference
D,O_SYNC count
4
Offset pointer
5
Reference count
▪ The kernel will use the file descriptor to index the process’s file
descriptor table to find file table entry to opened file.
▪ It checks the file table entry to make sure that the file is opened with
appropriate mode.
Version 1.0
Kernel support : read system call
▪ The kernel will check the type of file in the inode record and invokes
an appropriate driver function to initiate the actual data transfer
with a physical file.
▪ If the process calls lseek function then the changes are made
to the file pointer in file table, provided the file is not a character
device file, a FIFO file, or a symbolic link file as they follow only
sequential read and write operations.
Version 1.0
Kernel support : close system call
Version 1.0
Directory files
Directoryfunction Purpose
opendir Opens a directory file (returns DIR *)
readdir Reads next record from file
closedir closes a directory file
rewinddir Sets file pointer to beginning of file
▪ Unix system also provides telldir and seekdir function for random
access of different records in a directory file
Version 1.0
UNIX File APIs
Version 1.0
Open system call
Version 1.0
▪ Access mode flag Use
▪ O_APPEND
▪ O_CREAT
▪ O_EXCL
▪ O_TRUNC
▪ O_NONBLOCK
▪ O_NOCTTY
▪ O_SYNC
Version 1.0
Access modifier flags
▪ O_APPEND : appends data to end of file
▪ O_TRUNC : if the file already exists, discards its contents
and sets file size to zero
▪ O_CREAT : creates the file if it does not exist
▪ O_EXCL : used with O_CREAT only. This flag causes
open to fail if the file exists
▪ O_NONBLOCK : specifies that any subsequent read or
write on the file should be non blocking
Version 1.0
Ex : int fd;
fd=open(“/etc/passwd”,O_RDONLY);
fd=open(“foo.txt”,O_WRONLY|O_APPEND); like cat>>temp.c
fd=open(“../foo.txt”,O_WRONLY|O_TRUNC); like cat> temp.c
▪ Third argument Permission is required only when O_CREAT is specified and can be
specified by using octal numbers or symbolic constants
fd=open(“foo.txt”,O_WRONLY|O_CREAT|O_TRUNC,0644)
fd=open(“foo.txt”,O_WRONLY|O_CREAT|O_TRUNC,
S_IRUSR|S_IWUSR|S_IRGRP|S_IOTH
Version 1.0
Umask
▪ Prototype:
mode_t umask ( mode_t new_umask);
mode_t old_mask = umask (S_IXGRP|S_IWOTH|S_IXOTH);
/*removes execute permission from group and write&execute
permission from others*/
▪ the file is created with bit wise ANDing the ones compliment of the
calling process umask value
▪ Actual_permission = permission & ~umask_value
▪ Actual_permission=0557&(~031)=0546
Version 1.0
Creat
#include <sys/types.h>
#include <unistd.h>
Int creat (const char* pathname, mode_t mode)
Version 1.0
Read system call
▪ This function fetches a fixed size block of data from a file referenced
by a given file descriptor.
#include <sys/types.h>
#include <unistd.h>
ssize_t read (int fdesc ,void* buf, size_t size);
Version 1.0
Read system call contd
▪ Some unix systems return -1 and discard the contents of the buffer
and some restart the system call automatically.
▪ Ex :
#define BUFSIZE 100
int n; char buf[BUFSIZE];
while((n=read(fd,buf,BUFSIZE) >0)
Version 1.0
Write system call
▪ The write function puts a fixed size block of data to a file referenced by a
file descriptor
#include <sys/types.h>
#include <unistd.h>
ssize_t write (int fdesc ,void* buf, size_t size);
Version 1.0
Write system call
Ex:
# define BUFSIZE 8192
Int n; cahr buf[BUFSIZE];
N=write(fd,buf,BUFSIZE);
Version 1.0
Close system call
#include <unistd.h>
int close (int fdesc);
▪ Close function will de allocate system resources( file table entries and
memory buffer allocated to hold read/write file data).
▪ If a process terminates without closing all the files it has opened ,the kernel
will close those files for the process.
Version 1.0
fcntl system call
▪ This system call can be used to query or set access control flags and
the close-on-exec flag of any file descriptor.
#include <fcntl.h>
int fcntl (int fdesc ,int cmd,…..);
Version 1.0
fcntl system call CONTD
▪ F_SETFL : sets or clears control flags that are specified in the third
argument (allowed flags are O_APPEND & O_NDELAY).
Version 1.0
fcntl system call CONTD
int cur_flags=fcntl(fdesc,F_GETFL);
int fcntl(fdesc,F_SETFL,cur_flag|O_APPEND|O_NONBLOCK);
Version 1.0
fcntl system call CONTD
▪ The fcntl function can also be used to duplicate a file descriptor fdesc
with another file descriptor.
▪ the results are two file descriptors referencing the same file with
same access mode and sharing the same file pointer to read or write
the file.
▪ This feature is useful in redirection of std i/p and o/p.
Version 1.0
fcntl system call CONTD
▪ Fcntl can be used to implement dup and dup2 system calls as follows
▪ the dup function duplicates a file descriptor fdesc with the lowest
unused file descriptor of the calling process.
#define dup(fdesc) fcntl(fdesc,F_DUPFD,0);
▪ The dup2 function will duplicate a file descriptor fd1 using fd2 file
descriptor, regardless of whether fd2 is used to reference another file
#define dup2(fd1,fd2) close(fd2), fcntl(fd1,F_DUPFD,fd2)
Version 1.0
lseek system call
▪ The read and write system calls are always relative to the current
offset within a file.
▪ the lseek system call is used to change the file offset to a different
value
▪ Lseek allows a process to perform random access of data on any
opened file.
▪ lseek is incompatible with FIFO files,character device files and
symlink files.
▪ Prototype :
#include <sys/types.h>
#include <unistd.h>
Off_t lseek (int fdesc , off_t pos, int whence)
The return value of lseek is the new file offset address where the next
read or write operation will occur
Version 1.0
lseek system call
▪ The iostream class defines the tellg and seekg functions to allow
users to do random data access of any iostream object.
▪ Ex: lseek(fd,10,SEEK_CUR); lseek(fd,-10,SEEK_END);
Version 1.0
lseek system call
Version 1.0
link system call
▪ The link function creates a new link for existing file.
▪ The function does not create a new file ,rather it creates a new
pathname for an existing file.
▪ Prototype :
#include <unistd.h>
int link (const char* cur_link , const char* new_link) ;
Version 1.0
Unlink system call
▪ Deletes a link of an existing file.
▪ It decreases the hard link count attributes of the named file and
removes the filename entry of the link from a directory file
▪ The file is removed from thefile system if the hard link count is
zero and no process has any file descriptor referencing the file.
#include <unistd.h>
int unlink (const char* cur_link );
Version 1.0
READING THE INODE :Stat,fstat
#include <sys/types.h>
#include <unistd.h>
int stat (const char* path_name, struct stat* statv)
int fstat (const int fdesc, struct stat* statv)
Version 1.0
READING THE INODE :Stat,fstat contd
▪ Struct stat
{ dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
off_t st_size;
time_t st_atime;
time_t st_mtime
time_t st_ctime
};
▪ both the functions return value 0 on success and -1 on fail.
▪ The possible error values are pathname/file descripor is
invalid,process lacks the permission,the function
interrupted.
Version 1.0
READING THE INODE :Stat,fstat contd
Version 1.0
READING THE INODE :Stat,fstat contd
Version 1.0
READING THE INODE :Stat,fstat contd
Version 1.0
FILE AND RECORD LOCKING
▪ UNIX systems allow multiple processes to read and write the same
file concurrently.
Version 1.0
Shared and exclusive locks
▪ A read lock is also called a shared lock and a write lock is called an
exclusive lock.
▪ A write lock prevents other processes from setting any overlapping read
or write locks on the locked regions of a file.
Version 1.0
▪ A read lock allows processes to set overlapping read locks but not
write locks. Other processes are allowed to lock and read data from
the locked regions.
Version 1.0
▪ If a file lock is not mandatory, it is an advisory. An advisory lock is
not enforced by a kernel at the system call level
Version 1.0
Advisory locks
Version 1.0
FCNTL file locking
Cmd_flag Use
F_SETLK Sets a file lock. Do not block if this
cannot succeed immediately.
Version 1.0
▪ For file locking, the third argument is an address of a struct flock-typed
variable.
▪ This flock specifies a region of a file where the lock is to be set, unset or
queried.
struct flock
{
short l_type;
short l_whence;
off_t l_start;
off_t l_len;
pid_t l_pid;
};
Version 1.0
l_type and l_whence fields of flock
Version 1.0
l_whence value Use
Version 1.0
▪ The l_len specifies the size of a locked region beginning from the
start address defined by l_whence and l_start. If l_len is 0 then the
length of the lock is imposed on the maximum size and also as it
extends. It cannot have a –ve value.
▪ When fcntl is called, the variable contains the region of the file
locked and the ID of the process that owns the locked region. This is
returned via the l_pid field of the variable.
Version 1.0
LOCK PROMOTION AND SPLITTING
▪ If a process sets a read lock and then sets a write lock on the
file, then process will own only the write lock. This process
is called lock promotion.
Version 1.0
Mandatory locks can be achieved by setting the following attributes of a
file.
▪ Turn on the set-GID flag of the file.
▪ Turn off the group execute right of the file.
▪ If a process locks a file and then creates a child process via fork, the
child process will not inherit the lock.
Version 1.0
Program-1 to illustrate the locking mechanism
#include<fcntl.h>
int main ( )
{
int fd;
struct flock lock;
fd=open(“sample”,O_RDONLY);
lock.l_type=F_RDLCK; lock.l_whence=0; lock.l_start=50;
lock.l_len=100; fcntl(fd,F_SETLK,&lock);
}
Version 1.0
Program-2 to illustrate the locking mechanism
Program
#include<fcntl.h>
#include<iostream.h>
#include<stdlib.h>
int main()
{
char buf[50];
int fd=open("b.txt",O_RDWR);
struct flock f1;
f1.l_type=F_WRLCK;
f1.l_whence=SEEK_END;
f1.l_start=0;
f1.l_len=100;
fcntl(fd,F_GETLK,&f1);
Version 1.0
if(f1.l_type==F_RDLCK)
{
cout << f1.l_pid << " has put read lock" << endl;
// exit(0);
}
if(f1.l_type==F_WRLCK)
{
cout << f1.l_pid << " has put write lock" << endl;
//exit(0);
}
Version 1.0
f1.l_type=F_WRLCK;
f1.l_pid=getpid();
fcntl(fd,F_SETLKW,&f1);
sleep(10);
lseek(fd,-50,SEEK_END);
read(fd,buf,50);
cout << buf;
f1.l_type=F_UNLCK;
fcntl(fd,F_SETLK,&f1);
}
Version 1.0
Program-3 to illustrate the locking mechanism
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h
Version 1.0
if ((fd = open(argv[1], O_RDWR)) == -1)
{
perror("Can't open file");
exit(1);
}
Version 1.0
fl.l_type = F_WRLCK;
fl.l_pid = getpid();
if (fcntl(fd, F_SETLK, &fl) == -1)
{
perror("Can't set Exculsive Lock");
exit(1);
}
else if(fl.l_type!=F_UNLCK)
{
printf("File has been Exculsively Locked by
process:%d\n",fl.l_pid);
}
Version 1.0
else
{
printf("File is not Locked\n");
}
printf("Press ENTER to Release lock:\n");
getchar();
fl.l_type = F_UNLCK;
printf("File has been Unlocked\n");
fsize=lseek(fd,0,SEEK_END);
offset=fsize-50;
Version 1.0
lseek(fd,offset,SEEK_SET);
read(fd,buf,50);
printf("Last 50 Byte Content in the file is\n");
printf("====================================\n");
printf("%s\n",buf);
return 0;
}
Version 1.0
To Run Program
Create a file, here we are creating a file with name demo with the
following Content:
Version 1.0
OUTPUT
File is Not Locked by any Process
Press Enter to Lock the File
---------------------------------
File has been Exclusively Locked by process:4087
Version 1.0
Directory File APIs
Version 1.0
Directory File APIs
▪ To create a directory
int n = int mkdir (const char* path_name , mode_t mode);
Version 1.0
Difference between mkdir and mknod
Version 1.0
Directory File APIs
Version 1.0
DIRECTORY RELATED FUNCTIONS
Opendir:
DIR* opendir (const char* path_name);
▪ This opens the file for read-only
Readdir:
Dirent* readdir(DIR* dir_fdesc);
Version 1.0
DIRECTORY RELATED FUNCTIONS
Closedir :
int closedir (DIR* dir_fdesc);
Rewinddir :
void rewinddir (DIR* dir_fdesc);
Version 1.0
DIRECTORY RELATED FUNCTIONS
rmdir API:
int rmdir (const char* path_name);
▪ Used to remove the directory files. Users may also use the
unlink API to remove directories provided they have super
user privileges.
Version 1.0
Device file APIs
Version 1.0
Device file APIs
To create:
int mknod(const char* path_name, mode_t
mode, int device_id);
Version 1.0
MAJOR AND MINOR NUMBERS
Version 1.0
Device file APIs
▪ If O_NOCTTY flag is set in the open call, the kernel will not
set the character device file opened as the controlling
terminal in the absence of one.
▪ The O_NONBLOCK flag specifies that the open call and any
subsequent read or write calls to a device file should be
non blocking to the process.
Version 1.0
FIFO File APIs
▪ To create:
int mkfifo( const char* path_name, mode_t mode);
Version 1.0
How is synchronization provided?
Version 1.0
FIFO File APIs
Version 1.0
FIFO File APIs
Version 1.0
FIFO File APIs
Version 1.0
▪ Uses of the fds argument are:
▪ fds[0] is a file descriptor to read data from the FIFO
file.
Version 1.0
Symbolic Link File APIs
Version 1.0
Symbolic Link File APIs
To create :
int symlink (const char* org_link, const char* sym_link);
Version 1.0
Symbolic Link File APIs
Version 1.0