SlideShare a Scribd company logo
SYSTEMS PROGRAMMING
LECTURE 3
FILE IO
FILE I/O
• In this section we will cover unbuffered I/O
which is at the lowest level in UNIX
• Knowledge of fopen(), getc(), putc(),
fread() and fwrite() is assumed
• We will be using file descriptors instead of
FILE* objects
• All this allows for lower level access and direct
manipulation of files, symbolic links and
directories
• In the kernel all files are given a non-negative
integer as a reference up to OPEN_MAX
(defined in <limits.h>)
• Three files are always open:
• STDIN_FILENO: 0
• STDOUT_FILENO: 1
• STDERR_FILENO: 2
• All primitive file access goes through these file
descriptors
FILE DESCRIPTORS
FILE DESCRIPTORS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int oflag)
int open(const char * pathname,
int oflag, mode_t mode)
int close(int filedes);
OPENING A FILE
O_RDONLY
O_WRONLY exclusive
O_RDWR
O_APPEND
O_CREAT
O_EXCL error if O_CREAT on existing file
O_TRUNC set length to 0
O_SYNC reflect to physical I/O immediately
open oflag constants (OR’d togethor)
Open returns the lowest numbered
descriptor or -1 on error
OTHER FILE SYSTEM CALLS
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
return new file offset, -1 on error
ssize_t read (int fd, void *buff, size_t
nbytes);
ssize_t write(int fd, const void *buff, size_t
nbytes)
Return number of bytes, -1 on error
PROCESS⇓◊ FILE
• Each process contains a process descriptor entry
• This process descriptor contains a list of open
files and for each a pointer to the file table
entry
• The file table entry contains the current file
offset, file status and a pointer to the v-node
table entry
• The v-node structure contains the i-node together
with a pointer to all the functions that operate on
this file
V-NODE
• Each open file has a v-node structure that contains
information about the type of file and pointers to
functions that operate on the file
• For most files, the v-node also contains the i-node for
the file
• This information is read from disk when the file is
opened
• i-node contains the owner of the file, file size, pointers
to where the actual data blocks are on disk …
• v-nodes provide support for multiple file system types
on a single computer
PROCESS⇓◊ FILE
• This hierarchical structure allows more than one
process to have the same file open (sharing v-node
entries)
• In this case, each process would have a different file
offset
TWO PROCESSES SHARING A FILE
PROCESS ⇓◊ FILE
• When a file is opened for writing and the
offset exceeds the i-node file size, the i-node is
updated accordingly
• Periodically and when closing the file, the i-
node is rewritten to the file system
• There is always one unique v-node table per
file and it is stored in the kernel
• Child processes share the same file table entry
DUPLICATING FILES
• An existing file descriptor is duplicating by
either of the following functions
• Writing to a duplicated file descriptor changes
the offset of the original file and vice versa
#include <unist.h>
int dup(int filedes);
int dup(int filesdes, int filedes2);
DUPLICATING FILES
SYNC, FSYNC, FDATASYNC
• UNIX systems have a buffer cache or page cache in
the kernel through which most disk I/O passes
• When data is written to file data is normally copied
by the kernel into one of its buffers and queued for
writing to disk (delayed write)
• Kernel eventually writes all the delayed-write
blocks to disk, normally when it needs to reuse the
buffer
• To ensure consistency of the file system on disk with
the contents of the buffer cache, the sync, fsync
and fdatasync functions are provided
SYNC, FSYNC, FDATASYNC
• The sync function simply queues all the modified
block buffers for writing and returns
• fsync refers only to a single file and waits for
the disk writes to complete
• fdatasync is similar to fsync but affects only
the data portions of the file
#include <unist.h>
void sync(void)
int fsync(int filedes);
int fdatasync(int filedes);
FCNTL AND IOCTL
• fcntl is used to set or request properties of
opened files
• ioctl is a catch all function which gives raw
access to all file attributes
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <ioctl.h>
Int fcntl(int filedes, int cmd, …);
Int ioctl(int filedes, int request, …);
FCNTL AND IOCTL
• fcntl is used for five different purposes:
• Duplicate an existing file (F_DUPFD)
• Get/set file descriptor flags
(F_GESTF/F_SETFD)
• Get/set file status flags
(F_GETGL/F_SETFL)
• Get/set asynchronous I/O ownership
(F_GETOWN/F_SETOWN)
• Get/set records locks
(F_GETLK/F_SETLK/F_SETLKW)
STAT, FSTAT AND LSTAT
#include <sys/stat.h>
int stat(const char* restrict pathname,
struct stat *restrict buf);
int fstat(int filedes,
struct stat *restrict buf);
int lstat(const char* restrict pathname,
struct stat *restrict buf);
All return 0 if OK, 1 on error
STAT, FSTAT AND LSTAT
• Given a pathname (or file descriptor for an
open file), the stat (fstat) function returns
a structure of information about the
named/open file
• The lstat function return information about
a symbolic link
• The biggest user of the stat function is the ls
–l command, which returns all the information
of a file
FILE TYPES
• Most files on a UNIX system are either regular
files or directories. There are additional ones:
• Regular file: contains data of some form,
interpretation of which is left to the
application processing the file
• Directory file: a file that contains the names
of other files and pointers to information on
these files.
• Block special file: provides buffered I/O
access in fixed-sized units to devices
FILE TYPES
• Character special file: provides unbuffered I/O
access in variable sized units to devices
NOTE: all devices on a system are either block special
files of character special files
• FIFO: used for communication between
processes (sometimes called named PIPE)
• Socket: used for network communication
• Symbolic link: points to another file
• File type is encoded in st_mode in stat
structure
USER AND GROUP IDS
• Every process has six or more IDs associated
with it
Real user ID
Real group ID
Who we really are
Effective user ID
Effective group ID
Supplementary group
IDs
Used for file access
permission checks
Saved set-user-ID
Saved set-group-ID
Saved by exec function
PROCESS IDS
• Real IDs identify who we really are and are taken
from out entry in the password file when we log in
• Effective IDs determine our file access permissions
(see later)
• Saved set-user-IDs contain copies of the effective
IDs when a program is executed
• Normally, effective and real IDs are the same
• Every file has an owner and a group owner
• Process effective ID can be changed to be that of
the file’s owner (for example to run in su mode)
FILE ACCESS PERMISSIONS
• Nine permission bits for each file
• Whenever we want to open a file, we must have
execute permission in each directory mentioned in
the name
• We cannot create a new file to a directory unless
we have write permission
• To delete a file, we need write and execute
permission in the directory
• To run a program we must have execute
permission
FILE PERMISSION FUNCTIONS
• access: test file accessibility base on real IDs
• umask: set file mode creation mask for the
process
• chmod and fchmod: change file access
permissions
• chown, fchown and lchown: change user and
group ID of a file
FILE SYSTEMS
FILE SYSTEMS
FILE SYSTEMS
• i-node contains all information about the file (access
permission, size, pointers to data blocks …)
• Directory entry stores filename and i-node number
(and others like file length)
• Since i-node number in the directory entry points to
an i-node in the same file system we cannot have a
directory entry point to an i-node in a different file
system (ln doesn’t cross systems)
• When renaming a file the actual contents of the files
do not need to be moved, but a new directory entry
needs to be added which points to the existing i-
node, and unlink old entry
FILE LINKING FUNCTIONS
• link: creates a new directory entry that
references an existing path. Atomic
• unlink: remove an existing directory entry and
decrements link count of the file
• remove: for a file, identical to unlink; for a
directory it is identical to rmdir
• rename: rename a file or directory
MORE CALLS
• symlink: create a symbolic link
• readlink: open the link itself
• utime: get/set file access and modification time
• mkdir: create a new, empty directory
• rmdir: delete and empty directory (must contain
only . And .. Entries)
• Directory management calls: opendir, readdir,
rewinddir, closedir, telldir, seekdir,
chdir, fchdir, getcwd
STANDARD I/O LIBRARY
We’ll skip this section since you
should be C experts
PASSWORD FILE
• Every user is assigned a unique username which is
associated with a user ID and group ID
• Also every user has a password which is stored using
a one way algorithm that generates 13 printable
characters from 64 (newer version might not)
• All this information is stored in /etc/passwd and
optionally /etc/shadow for security
• Password file format:
username:password:UID:GID:Comment
field:initial directory:initial shell
• Every process is also assigned the UID and GID of the
process owner
PASSWORD FILE
• There is usually an entry with the user name root (0)
• Some fields of the password file entry can be empty
• Shell field contains the name of the executable
program to be used as the login shell
• The nobody username can be used to allow people
to log in to a system without any privileges
• finger allows additional information in the
comment field
• vipw command allows administrator to edit
password file
PASSWORD FILE
#include <pwd.h>
struct passwd* getpwuid(uid_t uid);
struct passwd* getpwnam(const char *name);
struct passwd* getpwent(void);
Return pointer if OK, NULL on error
void setpwent(void);
void endpwent(void);
SHADOW FILE
• Systems now store the encrypted password in a
different file, the shadow password file
• Avoid brute-force password hacking
• This contains the user name and encrypted password,
together with other field such as password change
fields
• This is not readable by the world, only a few
programs (login, passwd) can, which are often set-
user-ID root
• A separate set of function are available to access the
shadow password file
SHADOW FILE
• Systems now store the encrypted password in a
different file, the shadow password file
• Avoid brute-force password hacking
• This contains the user name and encrypted password,
together with other field such as password change
fields
• This is not readable by the world, only a few
programs (login, passwd) can, which are often set-
user-ID root
• A separate set of function are available to access the
shadow password file

More Related Content

What's hot

2nd unit part 1
2nd unit  part 12nd unit  part 1
2nd unit part 1
Pavan Illa
 
Lesson 1 Linux System Fundamentals
Lesson 1 Linux System Fundamentals  Lesson 1 Linux System Fundamentals
Lesson 1 Linux System Fundamentals
Sadia Bashir
 
Ch11 file system interface
Ch11 file system interfaceCh11 file system interface
Ch11 file system interface
Abdullah Al Shiam
 
File system
File systemFile system
File system
Harleen Johal
 
10 File System
10 File System10 File System
10 File System
Dr. Loganathan R
 
File Protection
File ProtectionFile Protection
File Protection
KRITI KATYAYAN
 
ITFT_File system interface in Operating System
ITFT_File system interface in Operating SystemITFT_File system interface in Operating System
ITFT_File system interface in Operating System
Sneh Prabha
 
Unix & Linux File System in Operating System
Unix & Linux File System in Operating SystemUnix & Linux File System in Operating System
Unix & Linux File System in Operating System
Meghaj Mallick
 
4.6 create and change hard and symbolic links v2
4.6 create and change hard and symbolic links v24.6 create and change hard and symbolic links v2
4.6 create and change hard and symbolic links v2
Acácio Oliveira
 
Course 102: Lecture 2: Unwrapping Linux
Course 102: Lecture 2: Unwrapping Linux Course 102: Lecture 2: Unwrapping Linux
Course 102: Lecture 2: Unwrapping Linux
Ahmed El-Arabawy
 
Course 102: Lecture 5: File Handling Internals
Course 102: Lecture 5: File Handling Internals Course 102: Lecture 5: File Handling Internals
Course 102: Lecture 5: File Handling Internals
Ahmed El-Arabawy
 
The linux file system structure
The linux file system structureThe linux file system structure
The linux file system structureTeja Bheemanapally
 
Basic Unix
Basic UnixBasic Unix
Basic Unix
Rajesh Kumar
 
Linux Directory Structure
Linux Directory StructureLinux Directory Structure
Linux Directory Structure
Kevin OBrien
 
A fast file system for unix presentation by parang saraf (cs5204 VT)
A fast file system for unix presentation by parang saraf (cs5204 VT)A fast file system for unix presentation by parang saraf (cs5204 VT)
A fast file system for unix presentation by parang saraf (cs5204 VT)
Parang Saraf
 

What's hot (20)

2nd unit part 1
2nd unit  part 12nd unit  part 1
2nd unit part 1
 
Unix File System
Unix File SystemUnix File System
Unix File System
 
Lesson 1 Linux System Fundamentals
Lesson 1 Linux System Fundamentals  Lesson 1 Linux System Fundamentals
Lesson 1 Linux System Fundamentals
 
Ch11 file system interface
Ch11 file system interfaceCh11 file system interface
Ch11 file system interface
 
File system
File systemFile system
File system
 
Os6
Os6Os6
Os6
 
10 File System
10 File System10 File System
10 File System
 
File Protection
File ProtectionFile Protection
File Protection
 
ITFT_File system interface in Operating System
ITFT_File system interface in Operating SystemITFT_File system interface in Operating System
ITFT_File system interface in Operating System
 
Unix cmc
Unix cmcUnix cmc
Unix cmc
 
Unix & Linux File System in Operating System
Unix & Linux File System in Operating SystemUnix & Linux File System in Operating System
Unix & Linux File System in Operating System
 
4.6 create and change hard and symbolic links v2
4.6 create and change hard and symbolic links v24.6 create and change hard and symbolic links v2
4.6 create and change hard and symbolic links v2
 
Course 102: Lecture 2: Unwrapping Linux
Course 102: Lecture 2: Unwrapping Linux Course 102: Lecture 2: Unwrapping Linux
Course 102: Lecture 2: Unwrapping Linux
 
Course 102: Lecture 5: File Handling Internals
Course 102: Lecture 5: File Handling Internals Course 102: Lecture 5: File Handling Internals
Course 102: Lecture 5: File Handling Internals
 
Host security
Host securityHost security
Host security
 
The linux file system structure
The linux file system structureThe linux file system structure
The linux file system structure
 
Basic Unix
Basic UnixBasic Unix
Basic Unix
 
Linux Directory Structure
Linux Directory StructureLinux Directory Structure
Linux Directory Structure
 
Linuxnishustud
LinuxnishustudLinuxnishustud
Linuxnishustud
 
A fast file system for unix presentation by parang saraf (cs5204 VT)
A fast file system for unix presentation by parang saraf (cs5204 VT)A fast file system for unix presentation by parang saraf (cs5204 VT)
A fast file system for unix presentation by parang saraf (cs5204 VT)
 

Viewers also liked

Halloween Party, Costume and Theme Ideas for Students
Halloween Party, Costume and Theme Ideas for StudentsHalloween Party, Costume and Theme Ideas for Students
Halloween Party, Costume and Theme Ideas for Students
HelpWithAssignment.com
 
Significance of information in marketing
Significance of information in marketingSignificance of information in marketing
Significance of information in marketing
HelpWithAssignment.com
 
International Accounting
International AccountingInternational Accounting
International Accounting
HelpWithAssignment.com
 
Quantum Assignment Help
Quantum Assignment HelpQuantum Assignment Help
Quantum Assignment Help
HelpWithAssignment.com
 
Proportions and Confidence Intervals in Biostatistics
Proportions and Confidence Intervals in BiostatisticsProportions and Confidence Intervals in Biostatistics
Proportions and Confidence Intervals in Biostatistics
HelpWithAssignment.com
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
HelpWithAssignment.com
 
Mothers day ideas for college students
Mothers day ideas for college studentsMothers day ideas for college students
Mothers day ideas for college studentsHelpWithAssignment.com
 
Forecasting Assignment Help
Forecasting Assignment HelpForecasting Assignment Help
Forecasting Assignment Help
HelpWithAssignment.com
 
Performance appraisal in human resource management
Performance appraisal in human resource managementPerformance appraisal in human resource management
Performance appraisal in human resource management
HelpWithAssignment.com
 
Rights of the Parties and Discharge; Remedies for Breach of Contract
Rights of the Parties and Discharge; Remedies for Breach of ContractRights of the Parties and Discharge; Remedies for Breach of Contract
Rights of the Parties and Discharge; Remedies for Breach of Contract
HelpWithAssignment.com
 
Target market selection
Target market selectionTarget market selection
Target market selection
HelpWithAssignment.com
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
HelpWithAssignment.com
 
Hypothesis Testing Assignment Help
Hypothesis Testing Assignment HelpHypothesis Testing Assignment Help
Hypothesis Testing Assignment Help
HelpWithAssignment.com
 
Constructivism assignment help
Constructivism assignment helpConstructivism assignment help
Constructivism assignment help
HelpWithAssignment.com
 

Viewers also liked (14)

Halloween Party, Costume and Theme Ideas for Students
Halloween Party, Costume and Theme Ideas for StudentsHalloween Party, Costume and Theme Ideas for Students
Halloween Party, Costume and Theme Ideas for Students
 
Significance of information in marketing
Significance of information in marketingSignificance of information in marketing
Significance of information in marketing
 
International Accounting
International AccountingInternational Accounting
International Accounting
 
Quantum Assignment Help
Quantum Assignment HelpQuantum Assignment Help
Quantum Assignment Help
 
Proportions and Confidence Intervals in Biostatistics
Proportions and Confidence Intervals in BiostatisticsProportions and Confidence Intervals in Biostatistics
Proportions and Confidence Intervals in Biostatistics
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
Mothers day ideas for college students
Mothers day ideas for college studentsMothers day ideas for college students
Mothers day ideas for college students
 
Forecasting Assignment Help
Forecasting Assignment HelpForecasting Assignment Help
Forecasting Assignment Help
 
Performance appraisal in human resource management
Performance appraisal in human resource managementPerformance appraisal in human resource management
Performance appraisal in human resource management
 
Rights of the Parties and Discharge; Remedies for Breach of Contract
Rights of the Parties and Discharge; Remedies for Breach of ContractRights of the Parties and Discharge; Remedies for Breach of Contract
Rights of the Parties and Discharge; Remedies for Breach of Contract
 
Target market selection
Target market selectionTarget market selection
Target market selection
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
Hypothesis Testing Assignment Help
Hypothesis Testing Assignment HelpHypothesis Testing Assignment Help
Hypothesis Testing Assignment Help
 
Constructivism assignment help
Constructivism assignment helpConstructivism assignment help
Constructivism assignment help
 

Similar to Systems Programming - File IO

File Management & Access Control
File Management & Access Control File Management & Access Control
File Management & Access Control
YuvrajWadavale
 
MODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptxMODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptx
ManasaPJ1
 
operating system File - System Interface
operating system File - System Interfaceoperating system File - System Interface
operating system File - System Interface
Chandrakant Divate
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
YourHelper1
 
Ch10 file system interface
Ch10   file system interfaceCh10   file system interface
Ch10 file system interface
Welly Dian Astika
 
Unit 7
Unit 7Unit 7
Unit 7siddr
 
Poking The Filesystem For Fun And Profit
Poking The Filesystem For Fun And ProfitPoking The Filesystem For Fun And Profit
Poking The Filesystem For Fun And Profit
ssusera432ea1
 
File system1.pptx
File system1.pptxFile system1.pptx
File system1.pptx
Samar954063
 
File system
File systemFile system
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X Systems
Sam Bowne
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
Tushar B Kute
 
Kernal
KernalKernal
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X Systems
Sam Bowne
 
Introduction to file system and OCFS2
Introduction to file system and OCFS2Introduction to file system and OCFS2
Introduction to file system and OCFS2
Gang He
 
Linux: Basics OF Linux
Linux: Basics OF LinuxLinux: Basics OF Linux
Linux: Basics OF Linux
Omkar Walavalkar
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X Systems
Sam Bowne
 
Linux Basics
Linux BasicsLinux Basics
Linux Basics
Lokesh C
 
Linux: Everyting-as-a-service
Linux: Everyting-as-a-serviceLinux: Everyting-as-a-service
Linux: Everyting-as-a-service
Rohit Sansiya
 
Unit 3 file management
Unit 3 file managementUnit 3 file management
Unit 3 file management
Kalai Selvi
 

Similar to Systems Programming - File IO (20)

File Management & Access Control
File Management & Access Control File Management & Access Control
File Management & Access Control
 
MODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptxMODULE 3.1 updated-18cs56.pptx
MODULE 3.1 updated-18cs56.pptx
 
operating system File - System Interface
operating system File - System Interfaceoperating system File - System Interface
operating system File - System Interface
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 
Windowsforensics
WindowsforensicsWindowsforensics
Windowsforensics
 
Ch10 file system interface
Ch10   file system interfaceCh10   file system interface
Ch10 file system interface
 
Unit 7
Unit 7Unit 7
Unit 7
 
Poking The Filesystem For Fun And Profit
Poking The Filesystem For Fun And ProfitPoking The Filesystem For Fun And Profit
Poking The Filesystem For Fun And Profit
 
File system1.pptx
File system1.pptxFile system1.pptx
File system1.pptx
 
File system
File systemFile system
File system
 
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X Systems
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 
Kernal
KernalKernal
Kernal
 
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X Systems
 
Introduction to file system and OCFS2
Introduction to file system and OCFS2Introduction to file system and OCFS2
Introduction to file system and OCFS2
 
Linux: Basics OF Linux
Linux: Basics OF LinuxLinux: Basics OF Linux
Linux: Basics OF Linux
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X Systems
 
Linux Basics
Linux BasicsLinux Basics
Linux Basics
 
Linux: Everyting-as-a-service
Linux: Everyting-as-a-serviceLinux: Everyting-as-a-service
Linux: Everyting-as-a-service
 
Unit 3 file management
Unit 3 file managementUnit 3 file management
Unit 3 file management
 

Recently uploaded

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Systems Programming - File IO

  • 2. FILE I/O • In this section we will cover unbuffered I/O which is at the lowest level in UNIX • Knowledge of fopen(), getc(), putc(), fread() and fwrite() is assumed • We will be using file descriptors instead of FILE* objects • All this allows for lower level access and direct manipulation of files, symbolic links and directories
  • 3. • In the kernel all files are given a non-negative integer as a reference up to OPEN_MAX (defined in <limits.h>) • Three files are always open: • STDIN_FILENO: 0 • STDOUT_FILENO: 1 • STDERR_FILENO: 2 • All primitive file access goes through these file descriptors FILE DESCRIPTORS
  • 4. FILE DESCRIPTORS #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int oflag) int open(const char * pathname, int oflag, mode_t mode) int close(int filedes);
  • 5. OPENING A FILE O_RDONLY O_WRONLY exclusive O_RDWR O_APPEND O_CREAT O_EXCL error if O_CREAT on existing file O_TRUNC set length to 0 O_SYNC reflect to physical I/O immediately open oflag constants (OR’d togethor) Open returns the lowest numbered descriptor or -1 on error
  • 6. OTHER FILE SYSTEM CALLS #include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); return new file offset, -1 on error ssize_t read (int fd, void *buff, size_t nbytes); ssize_t write(int fd, const void *buff, size_t nbytes) Return number of bytes, -1 on error
  • 7. PROCESS⇓◊ FILE • Each process contains a process descriptor entry • This process descriptor contains a list of open files and for each a pointer to the file table entry • The file table entry contains the current file offset, file status and a pointer to the v-node table entry • The v-node structure contains the i-node together with a pointer to all the functions that operate on this file
  • 8. V-NODE • Each open file has a v-node structure that contains information about the type of file and pointers to functions that operate on the file • For most files, the v-node also contains the i-node for the file • This information is read from disk when the file is opened • i-node contains the owner of the file, file size, pointers to where the actual data blocks are on disk … • v-nodes provide support for multiple file system types on a single computer
  • 9. PROCESS⇓◊ FILE • This hierarchical structure allows more than one process to have the same file open (sharing v-node entries) • In this case, each process would have a different file offset
  • 11. PROCESS ⇓◊ FILE • When a file is opened for writing and the offset exceeds the i-node file size, the i-node is updated accordingly • Periodically and when closing the file, the i- node is rewritten to the file system • There is always one unique v-node table per file and it is stored in the kernel • Child processes share the same file table entry
  • 12. DUPLICATING FILES • An existing file descriptor is duplicating by either of the following functions • Writing to a duplicated file descriptor changes the offset of the original file and vice versa #include <unist.h> int dup(int filedes); int dup(int filesdes, int filedes2);
  • 14. SYNC, FSYNC, FDATASYNC • UNIX systems have a buffer cache or page cache in the kernel through which most disk I/O passes • When data is written to file data is normally copied by the kernel into one of its buffers and queued for writing to disk (delayed write) • Kernel eventually writes all the delayed-write blocks to disk, normally when it needs to reuse the buffer • To ensure consistency of the file system on disk with the contents of the buffer cache, the sync, fsync and fdatasync functions are provided
  • 15. SYNC, FSYNC, FDATASYNC • The sync function simply queues all the modified block buffers for writing and returns • fsync refers only to a single file and waits for the disk writes to complete • fdatasync is similar to fsync but affects only the data portions of the file #include <unist.h> void sync(void) int fsync(int filedes); int fdatasync(int filedes);
  • 16. FCNTL AND IOCTL • fcntl is used to set or request properties of opened files • ioctl is a catch all function which gives raw access to all file attributes #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <ioctl.h> Int fcntl(int filedes, int cmd, …); Int ioctl(int filedes, int request, …);
  • 17. FCNTL AND IOCTL • fcntl is used for five different purposes: • Duplicate an existing file (F_DUPFD) • Get/set file descriptor flags (F_GESTF/F_SETFD) • Get/set file status flags (F_GETGL/F_SETFL) • Get/set asynchronous I/O ownership (F_GETOWN/F_SETOWN) • Get/set records locks (F_GETLK/F_SETLK/F_SETLKW)
  • 18. STAT, FSTAT AND LSTAT #include <sys/stat.h> int stat(const char* restrict pathname, struct stat *restrict buf); int fstat(int filedes, struct stat *restrict buf); int lstat(const char* restrict pathname, struct stat *restrict buf); All return 0 if OK, 1 on error
  • 19. STAT, FSTAT AND LSTAT • Given a pathname (or file descriptor for an open file), the stat (fstat) function returns a structure of information about the named/open file • The lstat function return information about a symbolic link • The biggest user of the stat function is the ls –l command, which returns all the information of a file
  • 20. FILE TYPES • Most files on a UNIX system are either regular files or directories. There are additional ones: • Regular file: contains data of some form, interpretation of which is left to the application processing the file • Directory file: a file that contains the names of other files and pointers to information on these files. • Block special file: provides buffered I/O access in fixed-sized units to devices
  • 21. FILE TYPES • Character special file: provides unbuffered I/O access in variable sized units to devices NOTE: all devices on a system are either block special files of character special files • FIFO: used for communication between processes (sometimes called named PIPE) • Socket: used for network communication • Symbolic link: points to another file • File type is encoded in st_mode in stat structure
  • 22. USER AND GROUP IDS • Every process has six or more IDs associated with it Real user ID Real group ID Who we really are Effective user ID Effective group ID Supplementary group IDs Used for file access permission checks Saved set-user-ID Saved set-group-ID Saved by exec function
  • 23. PROCESS IDS • Real IDs identify who we really are and are taken from out entry in the password file when we log in • Effective IDs determine our file access permissions (see later) • Saved set-user-IDs contain copies of the effective IDs when a program is executed • Normally, effective and real IDs are the same • Every file has an owner and a group owner • Process effective ID can be changed to be that of the file’s owner (for example to run in su mode)
  • 24. FILE ACCESS PERMISSIONS • Nine permission bits for each file • Whenever we want to open a file, we must have execute permission in each directory mentioned in the name • We cannot create a new file to a directory unless we have write permission • To delete a file, we need write and execute permission in the directory • To run a program we must have execute permission
  • 25. FILE PERMISSION FUNCTIONS • access: test file accessibility base on real IDs • umask: set file mode creation mask for the process • chmod and fchmod: change file access permissions • chown, fchown and lchown: change user and group ID of a file
  • 28. FILE SYSTEMS • i-node contains all information about the file (access permission, size, pointers to data blocks …) • Directory entry stores filename and i-node number (and others like file length) • Since i-node number in the directory entry points to an i-node in the same file system we cannot have a directory entry point to an i-node in a different file system (ln doesn’t cross systems) • When renaming a file the actual contents of the files do not need to be moved, but a new directory entry needs to be added which points to the existing i- node, and unlink old entry
  • 29. FILE LINKING FUNCTIONS • link: creates a new directory entry that references an existing path. Atomic • unlink: remove an existing directory entry and decrements link count of the file • remove: for a file, identical to unlink; for a directory it is identical to rmdir • rename: rename a file or directory
  • 30. MORE CALLS • symlink: create a symbolic link • readlink: open the link itself • utime: get/set file access and modification time • mkdir: create a new, empty directory • rmdir: delete and empty directory (must contain only . And .. Entries) • Directory management calls: opendir, readdir, rewinddir, closedir, telldir, seekdir, chdir, fchdir, getcwd
  • 31. STANDARD I/O LIBRARY We’ll skip this section since you should be C experts
  • 32. PASSWORD FILE • Every user is assigned a unique username which is associated with a user ID and group ID • Also every user has a password which is stored using a one way algorithm that generates 13 printable characters from 64 (newer version might not) • All this information is stored in /etc/passwd and optionally /etc/shadow for security • Password file format: username:password:UID:GID:Comment field:initial directory:initial shell • Every process is also assigned the UID and GID of the process owner
  • 33. PASSWORD FILE • There is usually an entry with the user name root (0) • Some fields of the password file entry can be empty • Shell field contains the name of the executable program to be used as the login shell • The nobody username can be used to allow people to log in to a system without any privileges • finger allows additional information in the comment field • vipw command allows administrator to edit password file
  • 34. PASSWORD FILE #include <pwd.h> struct passwd* getpwuid(uid_t uid); struct passwd* getpwnam(const char *name); struct passwd* getpwent(void); Return pointer if OK, NULL on error void setpwent(void); void endpwent(void);
  • 35. SHADOW FILE • Systems now store the encrypted password in a different file, the shadow password file • Avoid brute-force password hacking • This contains the user name and encrypted password, together with other field such as password change fields • This is not readable by the world, only a few programs (login, passwd) can, which are often set- user-ID root • A separate set of function are available to access the shadow password file
  • 36. SHADOW FILE • Systems now store the encrypted password in a different file, the shadow password file • Avoid brute-force password hacking • This contains the user name and encrypted password, together with other field such as password change fields • This is not readable by the world, only a few programs (login, passwd) can, which are often set- user-ID root • A separate set of function are available to access the shadow password file