You are on page 1of 56

INHA UNIVERSITY TASHKENT

FALL SEMESTER 2019

SOC 3100
OPERATING SYSTEMS
CREDITS/HOURS PER WEEK : 3/3

COURSE TYPE : TECHNICAL CORE SEQUENCE

INSTRUCTOR
DR. A. R. NASEER
DEAN & PROFESSOR OF COMPUTER SCIENCE & ENGG
9/25/2019 7:36 PM Lecture Slides on SOC3100 OPERATING SYSTEMS 1
Fall Semester 2019 @ Dr A R Naseer
INHA UNIVERSITY TASHKENT
FALL SEMESTER 2019

SOC 3100
OPERATING SYSTEMS
CLASS SCHEDULE
GROUP1 ICE-17-1 MON 13.30 – 15.00 WED 13.30 – 15.00(203)
GROUP2 CSE-17-1/ICE17-2 MON 15.00 – 16.30 WED 15.00 – 16.30(203)
GROUP3 CSE-17-2/17-3 TUE 09.00 – 10.30 THUR 09.00 – 10.30(203)
GROUP4 CSE-17-4 TUE 10.30 – 12.00 THUR 10.30 – 12.00(203)

9/25/2019 7:36 PM Lecture Slides on SOC3100 OPERATING SYSTEMS 2


Fall Semester 2019 @ Dr A R Naseer
SOC 3010
OPERATING SYSTEMS

WEEK 3

LINUX/UNIX SHELL
PROGRAMMING

9/25/2019 7:36 PM Lecture Slides on SOC3100 OPERATING SYSTEMS 3


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Shell Scripts
 The basic concept of a shell script is a list of
commands, which are listed in the order of execution.
 A good shell script will have comments, preceded by #
sign, describing the steps.
 There are conditional tests, such as value A is greater than
value B, loops allowing us to go through massive amounts
of data, files to read and store data, and variables to read
and store data, and the script may include functions.
 Shell scripts and functions are both interpreted. This
means they are not compiled.

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 4


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Example Script
 Assume we create a test.sh script.
 Note all the scripts would have the .sh extension.
 Before you add anything else to your script, you need to alert the
system that a shell script is being started.
 This is done using the shebang construct. For example −
#!/bin/bash
 This tells the system that the commands that follow are to be
executed by the Bourne Again shell. It's called a shebang because
the # symbol is called a hash, and the ! symbol is called a bang.
 To create a script containing these commands, you put the shebang
line first and then add the commands −
#!/bin/bash
pwd
ls
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 5
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Shell Comments
 You can put your comments in shell script as follows −
#!/bin/bash
# A simple sample script example
# Store the script in file test.sh
# Then make the script executable & Run
pwd
ls
 Save the above content in test.h and make the script
executable by
$chmod +x test.sh
 The shell script is now ready to be executed −
$./test.sh
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 6
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Shell Variables
 A variable is a character string to which we assign a value. The value
assigned could be a number, text, filename, device, or any other type of
data.
 A variable is nothing more than a pointer to the actual data.
❑ Variable Names
 The name of a variable can contain only letters a to z or A to Z , numbers 0
to 9 or the underscore character __ .
 By convention, Unix shell variables will have their names in UPPERCASE.
 The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2

 Following are the examples of invalid variable names −


2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 7


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Defining Variables
 Variables are defined as follows −
variable_name=variable_value
 For example −
GROUP=“JUNIOR CSE ICE"
 The above example defines the variable GROUP and assigns the value " JUNIOR
CSE ICE" to it. Variables of this type are called scalar variables. A scalar variable
can hold only one value at a time.
 Shell enables you to store any value you want in a variable. For example −
VAR1=“How are you?"
VAR2=200
❑ Accessing Values
 To access the value stored in a variable, prefix its name with the dollar sign ($)
 For example, the following script will access the value of defined variable GROUP
and print it on STDOUT −
#!/bin/sh
GROUP=“JUNIOR CSE ICE"
echo $GROUP
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 8
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ WRITING A SHELL SCRIPT - test.sh
#!/bin/bash
echo Hi, What is your name
read NAME
echo Good Morning $NAME
echo =============================================================
echo Your Home directory : $PWD
echo Environment variable PATH = $PATH
echo PRESS Enter KEY
read key

echo =============================================================
echo HARD DISK FREE SPACE INFO
free
echo PRESS Enter KEY
read key

echo =============================================================
echo PROCESSES CURRENTLY RUNNING
ps -la
echo PRESS Enter KEY
read key
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 9
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
echo =============================================================
echo LINUX VERSION
uname -a
echo PRESS Enter KEY
read key
echo =============================================================
echo WHO ARE CURRENTLY LOGGED IN
who -a
echo PRESS Enter KEY
read key
echo =============================================================
echo Do you want directory listing long or short \( enter 1 or 0 \)
read LONG
if [ $LONG -eq 1 ]
then
ls -la
else
ls
fi
echo PRESS Enter KEY
read key

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 10


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
echo =============================================================
echo ENTER A FILE NAME TO STORE 10 NAMES
read FILE
echo ENTER 10 NAMES ONE BELOW THE OTHER ON SEPARAT LINEs and THEN PRESS ^D
cat >> $FILE
echo PRESS Enter KEY
read key
echo =============================================================
echo your FILE $FILE CONTENTS
cat $FILE
echo PRESS Enter KEY
read key
echo =============================================================
echo FILE SORTING IN ALPHABETICAL ORDER
sort $FILE
echo PRESS Enter KEY
read key
echo =============================================================
echo FILE SORTING IN REVERSE ALPHABETICAL ORDER
sort –r $FILE
echo PRESS Enter KEY
read key

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 11


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
echo =================================================
echo Enter a filename to find number of characters, words and lines
read FNAME
cat $FNAME
echo No of lines
wc -l $FNAME
echo No of words
wc -w $FNAME
echo No of bytes
wc -c $FNAME
echo PRESS Enter KEY
read key

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 12


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
echo =================================================
A=1
B=0
C=1
echo Computing SUM OF FIRST n ODD INTEGERS
echo ENTER VALUE OF n=
read n
while [ $A -le $n ]
do
B=$(expr $B + $C)
A=$(expr $A + 1)
C=$(expr $C + 2)
done
echo Sum of FIRST $n odd numbers = $B
echo PRESS Enter KEY
read key

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 13


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
echo =================================================
echo Files in your HOME Directory with extension .c
for FILE in $HOME/*.c
do
echo $FILE
done
echo =================================================
A=1
B=1
echo Computing FACTORIAL OF n
echo ENTER VALUE OF n=
read n
until [ $A -gt $n ]
do
B=$(expr $B \* $A)
A=$(expr $A + 1)
done
echo FACTORIAL OF $n = $B
echo PRESS Enter KEY
read key
echo SIGNING OFF ...GOOD BYE
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 14
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
#!/bin/bash
echo COMPUTING SUM OF FIRST 100 INTEGERS
sum=0
for i in {1..100}
do
sum=$sum+$i
done
echo SUM OF FIRST 100 INTEGERS = $sum
echo =================================================
Create a shell script copy.sh to provide two command line arguments
#!/bin/bash
echo Copying file $1 to $2
cp $1 $2
echo file $1 CONTENTS
cat $1
echo file $2 CONTENTS
cat $2

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 15


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
#!/bin/bash
read -p 'Login name:' LOGIN
read -sp 'Password:' PASS
echo \n
echo Your LOGIN NAME IS $LOGIN
echo Your PASSWORD IS $PASS

echo TYPE NAMES OF YOUR THREE FRIENDS


read FRIEND1 FRIEND2 FRIEND3
echo YOUR FIRST FRIEND IS $FRIEND1
echo YOUR SECOND FRIEND IS $FRIEND2
echo YOUR THIRD FRIEND IS $FRIEND3
echo ============================================
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 16
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
#!/bin/bash
echo =================================================
echo Name of the Bash script - $0
echo How many arguments were passed to the Bash script - $#
echo All the arguments supplied to the bash script - $@
echo The exit status of the most recently run process $?
echo The process ID of the current script - $$
echo User Name of the user running the script - $USER
echo The hostname of the machine the script is running on - $HOSTNAME
echo The number of seconds since the script was started - $SECONDS
echo Current line number in the Bash script - $LINENO
echo Random number returned by the RANDOM variable - $RANDOM
echo VALUES OF ALL ENVIRONMENT VARIABLES SET UP IN THE CURRENT
ENVIRONMENT
env | more
echo =================================================

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 17


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
#!/bin/bash elif [ $CHOICE == cat ]
#A simple Menu System then
OPTIONS='ls longls who free linuxversion echo ENTER FILE NAME :
cat mv cp QUIT' read FILE
PS3='Choose an option:' cat $FILE
elif [ $CHOICE == mv ]
select CHOICE in $OPTIONS
then
do echo ENTER OLD FILE NAME :
if [ $CHOICE == ls ] read FILE1
then echo ENTER NEW FILE NAME :
ls read FILE2
mv $FILE1 $FILE2
elif [ $CHOICE == longls ]
elif [ $CHOICE == cp ]
then then
ls -la echo ENTER NAME OF FILE TO BE COPIED FROM:
elif [ $CHOICE == who ] read FILE1
then echo ENTER NAME OF FILE TO BE COPIED TO :
read FILE2
who -a
cp $FILE1 $FILE2
elif [ $CHOICE == free ] elif [ $CHOICE == QUIT ]
then then
free echo BYE ... BYE
elif [ $CHOICE == linuxversion ] break
fi
then
done
uname -a

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 18


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
#!/bin/bash case $CH in
loop=1 1)
while [ $loop -eq 1 ] ls
do ;;
2)
echo .....................................................................................
pwd
echo . MENU . ;;
echo . . 3)
echo . 1. LIST DIRECTORY CONTENTS . uname -r
echo . 2. SHOW CURRENT WORKING DIRECTORY . ;;
4)
echo . 3. DISPLAY LINUX VERSION .
free
echo . 4. SHOW FREE SPACE ON DISK . ;;
echo . 5. SHOW WHO ARE LGGED IN . 5)
echo . 6. DISPLAY CONTENTS OF A FILE . who -a
echo . 7. CREATE OR OPEN A FILE . ;;
6)
echo . 8. COPY A FILE .
echo Enter File Name :
echo . 9. RENAME A FILE . read FILE
echo . 10. REMOVE A FILE . cat $FILE
echo . 11. QUIT . ;;
echo ..................................................................................... 7)
echo Enter File Name :
echo ENTER YOUR CHOICE :
read FILE
read CH gedit $FILE
;;

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 19


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
8) if [ $OK -eq 1 ]
echo Enter Name of the File to be copied from : then
read FILE1 rm $FILE
echo Enter Name of the File to be copied to : echo File $FILE deleted.....OK
else
read FILE2
echo File $FILE not deleted.....OK
cp $FILE1 $FILE2 fi
;; ;;
9) 11)
echo Enter OLD File Name: echo QUITING.......GOOD BYE
read FILE1 break
echo Enter NEW File Name: ;;
read FILE2
*)
mv $FILE1 $FILE2
echo INVALID CHOICE - READ MENU
;;
CORRECTLY
10)
echo Enter Name of the File to delete:
;;
read FILE
esac
echo ARE YOU SURE - CONFIRM 1 OR 0 done
read OK

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 20


Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ SHELL FUNCTIONS
 Functions enable you to break down the overall functionality of a script into smaller,
logical subsections, which can then be called upon to perform their individual tasks
when needed.
❑ Creating Functions

 To declare a function, simply use the following syntax −

Function_name() {
List of commands
}
The function name must be followed by parentheses, followed by a list of commands
enclosed within braces.
Example :
#!/bin/bash
#Define your function here
Hello() {
echo “Hello World”
}
#Invoke your function
Hello
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 21
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
❑ Passing Parameters to a Example 2:
#!/bin/bash
Function #Define your function here
 You can define a function that Hello() {
will accept parameters while echo “Hello World $1 $2”
return 5
calling the function. These
}
parameters would be #Invoke your function
represented by $1, $2 and so Hello GOOD MORNING
on. #Capture the value returned by last command
rvalue= $?
echo “Return value is $rvalue”
Example 1: Nested Functions
#!/bin/bash One of the more interesting features of functions
is that they can call themselves and also other
#Define your function here functions
Hello() { func1() {
echo “currently in Function 1…”
echo “Hello World $1 $2” echo “Now invoking Function 2…”
func2
} }
#Invoke your function func2(){
echo “Currently in Function 2 ….”
Hello GOOD MORNING }
#calling function
9/25/2019 7:36 PM func1 22
Lecture Slides on SOC 3100 OPERATING SYSTEMS
Fall Semester 2019 @ Dr A R Naseer
SHELL SCRIPT
Using Arrays Example 3:
Example 1: #!/bin/bash
#!/bin/bash echo Enter size of the list :
list=(12 67 123 49 88 123 -9 0 456 126) read N
let I=0 echo Enter a list of $N numbers :
while [ $I -le 9 ] let K=0
do while [ $K -lt $N ]
echo ${list[$I]} do
let I=$I+1 read VAL
done list[$K]=$VAL
Example 2: let K=$K+1
#!/bin/bash done
list=(12 67 123 49 88 123 -9 0 456 126) let I=0
let I=0 max=${list[0]}
max=${list[0]} let I=+$I
let I=+$I while [ $I -lt $N ]
while [ $I -le 9 ] do
do if [ ${list[$I]} -gt $max ]
if [ ${list[$I]} -gt $max ] then
then max=${list[$I]}
max=${list[$I]} fi
fi let I=$I+1
let I=$I+1 done
done echo Maximum element in the list is : $max
9/25/2019 7:36 PM 23
echo Maximum element in the list is : $max Lecture Slides on SOC 3100 OPERATING SYSTEMS
Fall Semester 2019 @ Dr A R Naseer
SOC 3010
OPERATING SYSTEMS

WEEK 3 Lecture

OVERVIEW OF UNIX
FILESYSTEM

9/25/2019 7:36 PM Lecture Slides on SOC3010 OPERATING SYSTEMS 24


Fall Semester 2019 @ Dr A R Naseer
Overview of Unix File System
❑ Files
 A Unix file is an information container structured as a sequence of
bytes; the kernel does not interpret the contents of a file.
 From the user's point of view, files are organized in a tree-structured
namespace.
 All the nodes of the tree, except the leaves, denote directory names.
 A directory node contains information about the files and directories just
beneath it.
 A file or directory name consists of a sequence of arbitrary ASCII characters,
with the exception of / and of the null character \0.
 Most filesystems place a limit on the length of a filename, typically no
more than 255 characters.
 The directory corresponding to the root of the tree is called the root directory.
 By convention, its name is a slash (/).
 Names must be different within the same directory, but the same name may
be used in different directories.
9/25/2019 7:36 PM Lecture Slides on CIE 3010 OPERATING SYSTEMS 25
Fall Semester 2019 @ Dr A R Naseer
Regular Files
 A regular file contains arbitrary data
 Applications often distinguish between text files and binary
files
– Text files are regular files with only ASCII or Unicode
characters
– Binary files are everything else
 e.g., object files, JPEG images
– Kernel doesn’t know the difference!
 Text file is sequence of text lines
– Text line is sequence of chars terminated by newline char
(‘\n’)
 Newline is 0xa, same as ASCII line feed character (LF)

 End of line (EOL) indicators in other systems


– Linux and Mac OS: ‘\n’ (0xa)
 line feed (LF)
– Windows and Internet protocols: ‘\r\n’ (0xd 0xa)
 Carriage return (CR) followed by line feed (LF)
Overview of Unix File System
❑ Files
 Unix associates a current working directory with each process; it
belongs to the process execution context, and it identifies the directory
currently used by the process.
 To identify a specific file, the process uses a pathname, which consists
of slashes alternating with a sequence of directory names that lead to
the file.

 If the first item in the pathname is a slash, the pathname is said to be


absolute, because its starting point is the root directory.
 Otherwise, if the first item is a directory name or filename, the
pathname is said to be relative, because its starting point is the
process's current directory.

 While specifying filenames, the notations ".“ to denote the current


working directory and ".." to denote parent directory are also used.
 If the current working directory is the root directory, "." and ".." coincide.
9/25/2019 7:36 PM Lecture Slides on CIE 3010 OPERATING SYSTEMS 27
Fall Semester 2019 @ Dr A R Naseer
Directories
 Directory consists of an array of links
– Each link maps a filename to a file
 Each directory contains at least two entries
– . (dot) is a link to itself
– .. (dot dot) is a link to the parent directory in
the directory hierarchy
 Commands for manipulating directories
– mkdir: create empty directory
– ls: view directory contents
– rmdir: delete empty directory
Directory Hierarchy
 All files are organized as a hierarchy anchored by root
directory named / (slash)
/

bin/ dev/ etc/ home/ usr/

bash tty1 group passwd droh/ bryant/ include/ bin/

hello.c stdio.h sys/ vim

unistd.h

 Kernel maintains current working directory (cwd) for each


process
– Modified using the cd command
Pathnames
 Locations of files in the hierarchy denoted by pathnames
– Absolute pathname starts with ‘/’ and denotes path from
root
 /home/droh/hello.c

– Relative pathname denotes path from current working


directory
 ../home/droh/hello.c
/

bin/ dev/ etc/ home/ usr/

bash tty1 group passwd droh/ bryant/ include/ bin/

hello.c stdio.h sys/ vim

unistd.h
HARD & SOFT LINKS
❑ Hard and Soft Links
 A filename included in a directory is called a file hard link, or
more simply, a link.
 The same file may have several links included in the same directory
or in different ones, so it may have several filenames.
 The Unix command:
$ ln p1 p2
is used to create a new hard link that has the pathname p2 for a
file identified by the pathname p1.
 Hard links have two limitations:
➢ It is not possible to create hard links for directories.

➢ Links can be created only among files included in the same


filesystem.
 To overcome these limitations, soft links (also called symbolic
links) are used.
9/25/2019 7:36 PM Lecture Slides on CIE 3010 OPERATING SYSTEMS 31
Fall Semester 2019 @ Dr A R Naseer
HARD & SOFT LINKS
❑ SYMBOLIC LINKS
 Symbolic links are short files that contain an arbitrary pathname of
another file.
 The pathname may refer to any file or directory located in any filesystem; it
may even refer to a non-existent file.

 The Unix command:


$ ln -s p1 p2
creates a new soft link with pathname p2 that refers to pathname p1.

 When this command is executed, the filesystem extracts the directory part of
p2 and creates a new entry in that directory of type symbolic link, with the
name indicated by p2.
 This new file contains the name indicated by pathname p1.
 This way, each reference to p2 can be translated automatically into a
reference to p1.

9/25/2019 7:36 PM Lecture Slides on CIE 3010 OPERATING SYSTEMS 32


Fall Semester 2019 @ Dr A R Naseer
FILE TYPES
❑ File Types
 Unix files may have one of the following types:
➢ Regular file

➢ Directory

➢ Symbolic link

➢ Block-oriented device file

➢ Character-oriented device file

➢ Pipe and named pipe (also called FIFO)

➢ Socket

 The first three file types are constituents of any Unix filesystem.
 Device files are related both to I/O devices, and to device drivers
integrated into the kernel.
 Pipes and sockets are special files used for interprocess
communication

9/25/2019 7:36 PM Lecture Slides on CIE 3010 OPERATING SYSTEMS 33


Fall Semester 2019 @ Dr A R Naseer
File Types
 Each file has a type indicating its role in the
system
– Regular file: Contains arbitrary data
– Directory: Index for a related group of files
– Socket: For communicating with a process on
another machine

 Other file types


– Named pipes (FIFOs)
– Symbolic links
– Character and block devices
File Descriptor & Inode
❑ File Descriptor and Inode
 Unix makes a clear distinction between the contents of a file and the information about a
file.
 With the exception of device files and files of special filesystems, each file consists of a
sequence of bytes.
 The file does not include any control information, such as its length or an end-of-file
(EOF) delimiter.
 All information needed by the filesystem to handle a file is included in a data structure
called an inode.
 Each file has its own inode, which the filesystem uses to identify the file and contains
the following attributes:
➢ File type
➢ Number of hard links associated with the file•
➢ File length in bytes
➢ Device ID (i.e., an identifier of the device containing the file)
➢ Inode number that identifies the file within the filesystem
➢ UID of the file owner
➢ User group ID of the file
➢ Several timestamps that specify the inode status change time, the last access
time, and the last modify time
➢ Access rights and file mode 35
Lecture Slides on CIE 3010 OPERATING SYSTEMS
9/25/2019 7:36 PM
Unix I/O Overview
 A Linux file is a sequence of m bytes:
– B0 , B1 , .... , Bk , .... , Bm-1
 Cool fact: All I/O devices are represented as files:
– /dev/sda2 (/usr disk partition)
– /dev/tty2 (terminal)
 Even the kernel is represented as a file:
– /boot/vmlinuz-3.13.0-55-generic (kernel image)
– /proc (kernel data structures)

– All I/O devices, such as networks, disks, and terminals,


are modeled as files, and all input and output is performed
by reading and writing the appropriate files
Unix I/O Overview
 Elegant mapping of files to devices allows kernel to
export simple interface called Unix I/O:
– Opening and closing files
 open()and close()

– Reading and writing a file


 read() and write()

– Changing the current file position (seek)


 indicates next offset into file to read or write

 lseek()

B0 B1 ••• Bk-1 Bk Bk+1 • • •

Current file position = k


Opening Files
❑ Opening files:
➢ An application announces its intention to access an I/O device by
asking the kernel to open the corresponding file.

➢ The kernel returns a small nonnegative integer, called a descriptor, that


identifies the file in all subsequent operations on the file.

➢ The kernel keeps track of all information about the open file.
➢ The application only keeps track of the descriptor.

➢ Each process created by a Unix shell begins life with three open files:
▪ standard input (descriptor 0),

▪ standard output (descriptor 1), and

▪ standard error (descriptor 2).

➢ The header file <unistd.h> defines constants STDIN_ FILENO,


STDOUT_FILENO, and STDERR_FILENO, which can be used instead of
the explicit descriptor values.
Opening Files
 A process opens an existing file or creates a new file by calling the
open function:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(char *filename, int flags, mode_t mode);
Returns: new file descriptor if OK,−1on error

➢ The open function converts a filename to a file descriptor and returns


the descriptor number.

➢ The descriptor returned is always the smallest descriptor that is not


currently open in the process.

➢ The flags argument indicates how the process intends to access the
file:
❖ O_RDONLY: Reading only

❖ O_WRONLY: Writing only

❖ O_RDWR: Reading and writing

❖ The mode argument specifies the access permission bits of new files.
Opening Files
For example, here is how to open an existing file for reading:
fd = Open("foo.txt", O_RDONLY, 0);

➢ The flags argument can also be or’d with one or more bitmasks that
provide additional instructions for writing:

O_CREAT: If the file doesn’t exist, then create a truncated (empty)


version of it.
O_TRUNC: If the file already exists, then truncate it.
O_APPEND: Before each write operation, set the file position to the end
of the file.

➢ For example, here is how you might open an existing file with the intent
of appending some data:

fd = Open("foo.txt", O_WRONLY|O_APPEND, 0);


Opening Files
➢ The mode argument specifies the access permission bits of
new files.
➢ The potential users of a file fall into three classes:
▪ The user who is the owner of the file
▪ The users who belong to the same group as the file, not including the
owner
▪ All remaining users (others)•

➢ There are three types of access rights(access mode) -- read, write, and execute
for each of these three classes. Thus, the set of access rights associated with a
file consists of nine different binary flags
➢ The symbolic names for these bits are shown in Figure.
Opening Files
➢ As part of its context, each process has a umask that is set
by calling the umask function.
➢ When a process creates a new file by calling the open
function with some mode argument, then the access
permission bits of the file are set to mode & ~umask.
➢ For example, suppose we are given the following default values
for mode and umask:
#define DEF_MODE S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP| S_IROTH| S_IWOTH
#define DEF_UMASK S_IWGRP|S_IWOTH

➢ Then the following code fragment creates a new file in which the
owner of the file has read and write permissions, and all other
users have read permissions:
umask(DEF_UMASK);
fd = Open("foo.txt", O_CREAT|O_TRUNC|O_WRONLY, DEF_MODE);
Reading and writing files
❑ Reading and writing files
➢ A read operation copies n>0 bytes from a file to memory,
starting at the current file position k, and then incrementing k
by n.
➢ Given a file with a size of m bytes, performing a read
operation when k≥m triggers a condition known as end-of-
file(EOF), which can be detected by the application.
➢ There is no explicit “EOF character” at the end of a file.
➢ Similarly, a write operation copies n>0 bytes from memory to
a file, starting at the current file position k, and then updating
k.
– Reading and writing a file read() and write()
Reading and writing files
❑ Reading and writing files
➢ Applications perform input and output by calling the read and
write functions, respectively.
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t n);
Returns: number of bytes read if OK, 0 on EOF ,−1on error
ssize_t write(int fd, const void *buf, size_t n);
Returns: number of bytes written if OK, −1on error
➢ The read function copies at most n bytes from the current file position of
descriptor fd to memory location buf.
➢ A return value of −1 indicates an error, and a return value of 0 indicates
EOF.
➢ Otherwise, the return value indicates the number of bytes that were
actually transferred.
 The write function copies at most n bytes from memory location buf to the
current file position of descriptor fd.
Reading Files
 Reading a file copies bytes from the current file position to
memory, and then updates file position
char buf[512];
int fd; /* file descriptor */
int nbytes; /* number of bytes read */

/* Open file fd ... */


/* Then read up to 512 bytes from file fd */
if ((nbytes = read(fd, buf, sizeof(buf))) < 0) {
perror("read");
exit(1);
}

 Returns number of bytes read from file fd into buf


– Return type ssize_t is signed integer
– nbytes < 0 indicates that an error occurred
Writing Files
 Writing a file copies bytes from memory to the current file
position, and then updates current file position

char buf[512];
int fd; /* file descriptor */
int nbytes; /* number of bytes read */

/* Open the file fd ... */


/* Then write up to 512 bytes from buf to file fd
*/
if ((nbytes = write(fd, buf, sizeof(buf)) < 0) {
perror("write");
exit(1);
}

 Returns number of bytes written from buf to file fd


– nbytes < 0 indicates that an error occurred
Reading and writing files
 Figure shows a program that uses read and write calls to copy
the standard input to the standard output,1 byte at a time

int main(void)
{
char c;
while(read(STDIN_FILENO, &c, 1) != 0)
write(STDOUT_FILENO, &c, 1);
exit(0);
}
Changing the Current File Position
❑ Seek - Changing the current file position
➢The kernel maintains a file position k, initially 0, for each open file.
➢The file position is a byte offset from the beginning of a file.
➢An application can set the current file position k explicitly by performing
a seek operation
– Changing the current file position (seek)
 indicates next offset into file to read or write

 lseek()

B0 B1 ••• Bk-1 Bk Bk+1 • • •

Current file position = k


Changing the Current File Position
 Input and output are normally sequential: each read or write takes
place at a position in the file right after the previous one.
 When necessary, however, a file can be read or written in any arbitrary
order.
 The system call lseek provides a way to move around in a file without
reading or writing any data:
#include <unistd.h>
long lseek(int fd, long offset, int origin);
Return value from lseek is a long that gives the new position in the
file, or -1 if an error occurs.

 sets the current position in the file whose descriptor is fd to offset,


which is taken relative to the location specified by origin.

 Subsequent reading or writing will begin at that position.

 origin can be 0, 1, or 2 to specify that offset is to be measured from the


beginning, from the current position, or from the end of the file
respectively
Changing the Current File Position
 For example, to append to a file (the redirection >> in the
UNIX shell, or "a" for fopen), seek to the end before
writing:
lseek(fd, 0L, 2);

 To get back to the beginning (``rewind''),


lseek(fd, 0L, 0);

 Notice the 0L argument; it could also be written as (long)


0 or just as 0 if lseek is properly declared.

 With lseek, it is possible to treat files more or less like


arrays, at the price of slower access.
Closing Files
❑ Closing files
➢ When an application has finished accessing a file, it informs
the kernel by asking it to close the file.
➢ The kernel responds by freeing the data structures it created
when the file was opened and restoring the descriptor to a
pool of available descriptors.
➢ When a process terminates for any reason, the kernel closes
all open files and frees their memory resources.
– Finally, a process closes an open file by calling the close
function.
#include <unistd.h>
int close(int fd);
Returns: zero if OK, −1 on error

– Closing a descriptor that is already closed is an error.


Renaming and deleting a file
❑ Renaming and deleting a file
➢ To rename or delete a file, a process does not need to open
it. Indeed, such operations do not act on the contents of the
affected file, but rather on the contents of one or more
directories.
➢ For example, the system call:

res = rename(oldpath, newpath);


changes the name of a file link,
➢ While the system call:

res = unlink(pathname);
decreases the file link count and removes the corresponding
directory entry. The file is deleted only when the link count
assumes the value 0.
– Closing a descriptor that is already closed is an error.
SOC 3010 OPERATING SYSTEMS
Reading Assignments

Chapter 1 of Text Book

Text Book

➢ Understanding the Linux Kernel


- Daniel P/ Bovet and Marco Cesati
Edition, O’ Reilly Media 2005, ISBN 978-0596005658

9/25/2019 7:36 PM Lecture Slides on SOC 3010 OPERATING SYSTEMS Fall 53


Semester 2019 @ Dr A R Naseer
SOC 3100
OPERATING SYSTEMS

COMPILING & BUILDING


LINUX KERNEL FROM
SOURCE

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 54


Fall Semester 2019 @ Dr A R Naseer
Compile & Build Linux Kernal from Source

STEPS:
$cd linux-source-4.4.0
$sudo apt-get install libncurses5 libncurses5-dev

$make menuconfig
$sudo apt-get update && sudo apt-get install libssl-dev
$make Clean

$make deb-pkg

$cd ..
$ls *.deb
9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 55
Fall Semester 2019 @ Dr A R Naseer
Compile & Build Linux Kernal from Source

STEPS:

*Testing the new Kernel


$sudo dpkg -i linux*4.4.16_4.4.16-1*.deb

$sudo reboot

9/25/2019 7:36 PM Lecture Slides on SOC 3100 OPERATING SYSTEMS 56


Fall Semester 2019 @ Dr A R Naseer

You might also like