System Programming
System Programming
System Programming
Dr. Parag Tamhankar
What will we learn today?
• Session 1 - Directories and Files in UNIX / Linux system. Basic UNIX commands
• The computer programs that allocate the system resources and coordinate all the details of the computer's internals is
called the operating system or the kernel.
• Users communicate with the kernel through a program known as the shell. The shell is a command line interpreter; it
translates commands entered by the user and converts them into a language that is understood by the kernel.
• Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson, Dennis Ritchie, Douglas McIlroy,
and Joe Ossanna at Bell Labs.
• There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are a few examples. Linux is
also a flavor of Unix which is freely available.
• Several people can use a Unix computer at the same time; hence Unix is called a multiuser system.
• A user can also run multiple programs at the same time; hence Unix is a multitasking environment.
Unix Architecture
• The main concept that unites all the versions of Unix is the following four basics −
• Kernel − The kernel is the heart of the operating system.
• It interacts with the hardware and most of the tasks like memory management, task scheduling and file management.
• Commands and Utilities − There are various commands and utilities which you can make use of in your day to day
activities.
• cp, mv, cat and grep, etc. are few examples of commands and utilities.
• Files and Directories − All the data of Unix is organized into files.
• All files are then organized into directories. These directories are further organized into a tree-like structure called the
filesystem.
Unix Architecture
Unix Architecture
• The block diagram of the UNIX OS kernel shows
various modules and their relationships with each
other. It shows the file subsystem on the left side and
the process control subsystem on the right.
• The figure also shows three levels i.e user, kernel, and
hardware.
• The system call and library interface made the border
between user programs and the kernel.
• System calls look like ordinary function calls in C
programs.
• Libraries map these function calls to the primitives
needed to enter the operating system.
• Assembly language programs may invoke system calls
directly without a system call library.
• Programs frequently use other libraries such as the
standard I/O library to provide a more sophisticated
use of the system calls.
What is Unix ?
• The file subsystem
• The file subsystem manages files, allocating file space, administering free space, controlling access
to files, and retrieving data for users.
• Processes interact with the file subsystem via a specific set of system calls, such as
• open (to open a file for reading or writing), close, read, write,
• stat (query the attributes of a file),
• chown (change the record of who owns the file), and
• chmod (change the access permissions of a file).
• Device drivers are the kernel modules that control the operation of peripheral devices.
What is Unix ?
• The process control subsystem
• The process control subsystem is responsible for process synchronization, interprocess communication, memory
management, and process scheduling.
• The file subsystem and the process control subsystem interact when loading a file into memory for execution.
• Some of the system calls for controlling processes are fork (create a new process),
• exec (overlay the image of a program onto the running process),
• exit(finish executing a process), wait (synchronize process execution with the exit of a previously forked process),
• brk (control the size of memory allocated to a process), and
• signal (control process response to extraordinary events).
• The swapper process is sometimes called the scheduler because it "schedules" the allocation of
memory for processes and influences the operation of the CPU scheduler.
• It schedules them to run in turn until they voluntarily relinquish the CPU while awaiting a resource
or until the kernel preempts them when their recent run time exceeds a time quantum.
• The scheduler then chooses the highest priority eligible process to run; the original process will run
again when it is the highest priority eligible process available
Shell Commands of UNIX
• Unix Commands
• When you first log into a unix system, you are presented with
something that looks like the following:
/home/jaya#
14
BITS Pilani
Unix Commands
• Unix is also case-sensitive. This means that cat and Cat are different
commands.
15
BITS Pilani
Unix Commands
Steven Bourne wrote the original unix shell sh,and most shells since
then end in the letters sh to indicate they are extentions on the original
idea.
Linux comes with a Bourne shell called bash written by the Free
Software Foundation.
Bash stands for Bourne Again Shell and is the default shell to use
running linux 16
BITS Pilani
Unix Commands
The man command displays reference pages for the command you specify.
The UNIX man pages (man is short for manual ) cover every command available.
To search for a man page, enter man followed by the name of the command to find .
For example:
$ man ls
17
BITS Pilani
Unix - Basics
• Login Unix
• When you first connect to a Unix system, you usually see a prompt such as the following −
• login:
• To log in
• Type your userid at the login prompt, then press ENTER.
• Your userid is case-sensitive, so be sure you type it exactly as your system administrator has instructed.
• login : krishna
• krishna's password:
• Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
• $
Unix - Basics
• Change Password
• All Unix systems require passwords to help ensure that your files and data remain your own and that the system
itself is secure from hackers and crackers.
• Following are the steps to change your password −
• Step 1 − To start, type password at the command prompt as shown below.
• Step 2 − Enter your old password, the one you're currently using.
• Step 3 − Type in your new password.
• Step 4 − You must verify the password by typing it again.
• $ passwd
• Changing password for krishna
• (current) Unix password:******
• New UNIX password:*******
• Retype new UNIX password:*******
• passwd: all authentication tokens updated successfully
Unix - Basics
• Who Are You?
• While you're logged into the system, you might be willing to know : Who am I?
• $ who am i
• krishna
• Ordinary Files − An ordinary file is a file on the system that contains data, text, or program
instructions. In this tutorial, you look at working with ordinary files.
• Special Files − Some special files provide access to hardware such as hard drives, CD-ROM drives,
modems, and Ethernet adapters.
UNIX files and directories
UNIX files and directories
• Listing Files
• To list the files and directories stored in the current directory, use the following command −
• $ ls
• bin hosts lib res.03
• ch07 hw1 pub test_results
• ch07.bak hw2 res.01 users
• docs hw3 res.02 work
• The command ls supports the -l option which would help you to get more information about the
listed files −
• $ ls -l
• drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
• -rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
• drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
• drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
• -rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
UNIX files and directories
• Listing Files
• $ ls –
• You can give multiple files and get information about those files at a time. Following is simple syntax −
• Renaming Files
• To change the name of a file, use the mv command. Following is the basic syntax −
• $ mv old_file new_file
• The mv command will move the existing file completely into the new file.
• Deleting Files
• To delete an existing file, use the rm command. Following is the basic syntax −
• $ rm filename
• Caution − A file may contain useful information. It is always recommended to be careful while using this Delete command.
• It is better to use the -i option along with rm command. It will ask for a confirmation before delete
• You can remove multiple files at a time with the command given below −
• $ rm filename1 filename2 filename3
What’s in the File?
There are two major commands used in unix for listing files, cat, and more.
cat
• cat shows the contents of the file.
cat [-nA] [file1 file2 . . . fileN]
• cat is not a user friendly command-it doesn’t wait for you to read the file, and is
mostly used in conjuction with pipes.
BITS Pilani
• more
• more is much more useful, and is the command that you’ll want to use when browsing
ASCII text files
more [-l] [+linenumber}] [file1 file2 ... fileN]
• The only interesting option is l, which will tell more that you aren't interested in treating
the character Ctrl-L} as a ``new page'' character. more will start on a specified
linenumber.
• head
head will display the first ten lines in the listed files.
head [- lines}] [l file1 file2 ... fileN]
• Any numeric option will be taken as the number of lines to print, so head -15 frog will
print the first fifteen lines of the file frog
31
BITS Pilani
• tail
• Like head, tail display only a fraction of the file.
• tail also accepts an option specifying the number of lines.
tail [-lines] [l file1 file2 ... fileN]
• file
• file command attempts to identify what format a particular file is written in.
32
BITS Pilani
• grep
• grep is the generalized regular expression parser.
• This is a fancy name for a utility which can only search a text file.
•
grep [-nvwx] [-number] { expression} [file1 file2 ... fileN]
33
BITS Pilani
UNIX files and directories
• Standard Unix Streams
• Under normal circumstances, every Unix program has three streams opened for it when it starts up
• stdin − This is referred to as the standard input and the associated file descriptor is 0.
• This is also represented as STDIN.
• The Unix program will read the default input from STDIN.
• stdout − This is referred to as the standard output and the associated file descriptor is 1.
• This is also represented as STDOUT.
• The Unix program will write the default output at STDOUT
• stderr − This is referred to as the standard error and the associated file descriptor is 2.
• This is also represented as STDERR.
• The Unix program will write all the error messages at STDERR.
Unix / Linux - Directory Management
• A directory is a file the solo job of which is to store the file names and the related information.
• All the files, whether ordinary, special, or directory, are contained in directories.
• Unix uses a hierarchical structure for organizing files and directories.
• This structure is often referred to as a directory tree.
• The tree has a single root node, the slash character (/), and all other directories are contained below it.
• Home Directory
• The directory in which you find yourself when you first login is called your home directory.
• You will be doing much of your work in your home directory and subdirectories that you'll be creating to
organize your files.
• You can go in your home directory anytime using the following command −
• $cd ~
• Here ~ indicates the home directory
Unix / Linux - Directory Management
• Absolute/Relative Pathnames
• Directories are arranged in a hierarchy with root (/) at the top.
• The position of any file within the hierarchy is described by its pathname.
• Elements of a pathname are separated by a /.
• A pathname is absolute, if it is described in relation to root, thus absolute pathnames always begin with a /.
• Following are some examples of absolute filenames.
• /etc/passwd
• /users/sjones/chem/notes
• /dev/rdsk/Os3
• A pathname can also be relative to your current working directory.
• Relative pathnames never begin with /.
• Relative to user krishna's home directory, some pathnames might look like this −
• chem/notes
• personal/res
• To determine where you are within the filesystem hierarchy at any time, enter the command pwd to print the current working
directory −
• $pwd
• /user0/home/krishna
Unix / Linux - Directory Management
• Listing Directories
• To list the files in a directory, you can use the following syntax −
• $ls dirname (e.g. $ls demo)
• Creating Directories
• We will now understand how to create directories. Directories are created by the following command −
• $mkdir dirname
• Creates the directory mydir in the current directory. Here is another example −
• $mkdir /tmp/test-dir
• This command creates the directory test-dir in the /tmp directory. The mkdir command produces no output if
it successfully creates the requested directory.
• If you give more than one directory on the command line, mkdir creates each of the directories. For example, −
• $mkdir docs pub
• Creates the directories docs and pub under the current directory.
Unix / Linux - Directory Management
• Removing Directories
• Directories can be deleted using the rmdir command as follows −
• $rmdir dirname
• Note − To remove a directory, make sure it is empty which means there should not be any file or sub-directory inside this directory.
• You can remove multiple directories at a time as follows −
• $rmdir dirname1 dirname2 dirname3
• The above command removes the directories dirname1, dirname2, and dirname3, if they are empty. The rmdir command produces
no output if it is successful.
• Changing Directories
• You can use the cd command to do more than just change to a home directory. You can use it to change to any directory by
specifying a valid absolute or relative path. The syntax is as given below −
• $cd dirname
• Here, dirname is the name of the directory that you want to change to. For example, the command −
• $cd /usr/local/bin
• Changes to the directory /usr/local/bin.
• From this directory, you can cd to the directory /usr/home/amrood using the following relative path −
• $cd ../../home/amrood
Unix / Linux - Directory Management
• Renaming Directories
• The mv (move) command can also be used to rename a directory. The syntax is as follows −
• $mv olddir newdir
• You can rename a directory mydir to yourdir as follows −
• $mv mydir yourdir
• The directories . (dot) and .. (dot dot)
• The filename . (dot) represents the current working directory; and the filename .. (dot dot) represents the
directory one level above the current working directory, often referred to as the parent directory.
• If we enter the command to show a listing of the current working directories/files and use the -a option to
list all the files and the -l option to provide the long listing, we will receive the following result.
• $ls -la
• drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 .
• drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
• ---------- 1 teacher class 4210 May 1 08:27 .profile
• -rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo
Unix / Linux - File Permission / Access Modes
• File ownership is an important component of Unix that provides a secure method for storing files.
• Every file in Unix has the following attributes −
• Owner permissions − The owner's permissions determine what actions the owner of the file can perform on the file.
• Group permissions − The group's permissions determine what actions a user, who is a member of the group that a file belongs to, can perform on
the file.
• Other (world) permissions − The permissions for others indicate what action all other users can perform on the file.
• The Permission Indicators
• While using ls -l command, it displays various information related to file permission as follows −
• $ls -l /home/amrood
• -rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
• drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
• Here, the first column represents different access modes, i.e., the permission associated with a file or a directory.
• The permissions are broken into groups of threes, and each position in the group denotes a specific permission, in this order: read (r), write (w),
execute (x) −
• The first three characters (2-4) represent the permissions for the file's owner.
• For example, -rwxr-xr-- represents that the owner has read (r), write (w) and execute (x) permission.
• The second group of three characters (5-7) consists of the permissions for the group to which the file belongs.
• For example, -rwxr-xr-- represents that the group has read (r) and execute (x) permission, but no write permission.
• The last group of three characters (8-10) represents the permissions for everyone else.
• For example, -rwxr-xr-- represents that there is read (r) only permission
Unix / Linux - File Permission / Access Modes
• File Access Modes
• The permissions of a file are the first line of defense in the security of a Unix system. The basic building
blocks of Unix permissions are the read, write, and execute permissions, which have been described below −
• Read - Grants the capability to read, i.e., view the contents of the file.
• Write - Grants the capability to modify, or remove the content of the file.
• Execute - User with execute permissions can run a file as a program.
• Here's an example using testfile. Running ls -1 on the testfile shows that the file's permissions are as follows −
• $ls -l testfile
• -rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Unix / Linux - File Permission / Access Modes
• Changing Permissions
• $chmod o+wx testfile
• $ls -l testfile
• -rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
• $chmod u-x testfile
• $ls -l testfile
• -rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
• $chmod g = rx testfile
• $ls -l testfile
• -rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
• Then each example chmod command from the preceding table is run on the testfile, followed by ls –l, so you can see the permission
changes −
• $ chmod 755 testfile
• $ls -l testfile
• -rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
• Changing Ownership
• The chown command changes the ownership of a file. The basic syntax is as follows −
• $ chown user filelist
• The value of the user can be either the name of a user on the system or the user id (uid) of a user on the system.
• The following example will help you understand the concept −
• $ chown amrood testfile
• Changes the owner of the given file to the user amrood.
• NOTE − The super user, root, has the unrestricted capability to change the ownership of any file but normal users
can change the ownership of only those files that they own.
Unix / Linux - File Permission / Access Modes
• Changing Group Ownership
• The chgrp command changes the group ownership of a file.
• The basic syntax is as follows −
• For example, first we set a variable TEST and then we access its value using the echo command −
• $TEST="Unix Programming"
• $echo $TEST
• It produces the following result.
• Unix Programming
• Note that the environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix.
• These variables retain their values until we come out of the shell.
Unix / Linux - File Permission / Access Modes
• Unix / Linux - Environment
• When you log in to the system, the shell undergoes a phase called initialization to set up the environment.
• This is usually a two-step process that involves the shell reading the following files −
• /etc/profile
• profile
• The process is as follows −
• The shell checks to see whether the file /etc/profile exists.
• If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed.
• The shell checks to see whether the file .profile exists in your home directory.
• Your home directory is the directory that you start out in after you log in.
• If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed.
• As soon as both of these files have been read, the shell displays a prompt −
• $
• This is the prompt where you can enter commands in order to have them executed.
• Note − The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used
by bash and ksh.
Unix / Linux - File Permission / Access Modes
• The .profile File
• The file /etc/profile is maintained by the system administrator of your Unix machine and
contains shell initialization information required by all users on a system.
spell
spell is very simple unix spelling program, usually for American English.
spell is a filter, like most of the other programs we’ve talked about.
52
BITS Pilani
cmp
• cmp compares two files.
• The first must be listed on command line, while the second is either listed
as the second parameter or is read in form standard input.
•
• cmp is very simple, and merely tells you where the two files first differ.
• $ cmp file1 [ file2]
53
BITS Pilani
diff
• The GNU version of diff has over twenty command line options.
• It is a much more powerful version of cmp and shows you what the differences are
instead of merely telling you where the first one is.
54
BITS Pilani
tr
55
BITS Pilani
ed command
• red is a restricted ed: it can only edit files in the current directory and cannot execute
shell commands.
• If invoked with a file argument, then a copy of file is read into the editor’s buffer.
• Changes are made to this copy and not directly to file itself.
• Upon quitting ed, any changes not explicitly saved with a ‘w’ command are lost.
56
BITS Pilani
ed command
BITS Pilani
pr command
• pr command:
• The pr command is famous for printing a file neatly on a page -- with margins at top
and bottom, filename, date, and page numbers.
• It can also print text in columns: one file per column or many columns for each file.
• The -t option takes away the heading and margins at the top and bottom of each page.
That's useful when "pasting" data into columns with no interruptions.
58
BITS Pilani
pr command
• The -m option reads all files on the command line simultaneously and prints each in its
own column, like this:
59
BITS Pilani
pr command
• % pr -3 file1
BITS Pilani
pr command
+n starts displaying with the nth page of each file. The default for n is 1.
-n displays n columns of output. This is the obsolete equivalent of -c n.
-a orders input lines across the page on output, instead of down. You should only use this
option with -n.
-c n displays n columns of output. When you specify this option, pr behaves as though
you had also specified the
-e and -i options. When you specify both this option and
-t, pr uses the minimum number of lines possible to display the output. You should not
specify this option with -m.
BITS Pilani
pr command
-e[char][gap] expands each occurrence of the input tab character to a string of spaces
such that the following character has the next column position which is a positive
multiple of gap, plus 1.
BITS Pilani
which
• Displays a path name of a command.
• Searches a path environmental variable for the command and displays
the absolute path.
• To find which tcsh and bash are actually in use, type:
% which tcsh
% which bash
• % man which for more details
chsh
• Change Login Shell
• Login shell is the shell that interprets commands after you logged in
by default.
• You can change it with chsh (provided that your system admin
allowed you to do so).
• To list all possible shells, depending on implementation:
% chsh -l
% cat /etc/shells
• % chsh with no arguments will prompt you for the shell.
whereis
• Display all locations of a command (or some other binary, man page, or a
source file).
• Searchers all directories to find commands that match whereis’
argument
• % whereis tcsh
date
• Guess what :-)
• Displays dates in various formats
• % date
• % date -u
• in GMT
• % man date
cal
• Calendar • % cal current month
• for month • % cal 2 2000 Feb 2000, leap
year
• entire year
• % cal 2 2100 not a leap year
• Years range: 1 - 9999 • % cal 2 2400 leap year
• No year 0 • % cal 9 1752 11 days skipped
SysPgm SysPgm1
Absolute and
Relative path
addressing
– All platforms have a method for describing the paths
for files and directories
– You usually specify a path as a series of names
separated by separator characters
– Typically, the first name is the top level of the
hierarchical specification of the path. The last name is
the file or directory the path identifies.
– A path can be Relative or Absolute
Absolute path
Systems Programming
Absolute path
To write an absolute path-name:
• Start at the root directory ( / ) and work down.
• Write a slash ( / ) after every directory name
Ex: $cat data.lst
• will work only if the file “data.lst” exists in your current
directory. However, if this file is not present in your
working directory and is present somewhere else say in
/home/Wipro/WASE, then this command will work only if
you will use it like shown below:
• cat /home/Wipro/WASE/data.lst
Systems Programming
Basic Linux
commands
• Absolute path
– Describes the location of a file or directory
starting from the top level of the file system.
• Examples
– cd /home/SysPgm
– cd /home/SysPgm/dir0/dirX
Relative path
• UNIX offers a shortcut in the relative pathname– that uses either the current or
parent directory as reference and specifies the path relative to it. A relative
path-name uses one of these cryptic symbols:
Systems Programming
Basic Linux
commands
• Relative
– “ ../Public”
– Can travel only along the links. There is no direct link
between “Download” and “Public”
– First traverse through the node “SysPgm” (parent
directory accessed with the help of ..) and then reach
“Public”
– If you were in directory named home, then the path
would be “SysPgm/Public”
– depending on relative location in the hierarchy tree,
path to the destination address changes. Hence the
name, Relative Path Addressing
Basic Linux
commands
• Relative path
– Describes the location of a file or directory relative
to an arbitrary location in the file system
• Examples
– cd ..
– cd ../dir0
Basic Linux
commands
• A path does not necessarily go from the top of
the hierarchy down to the target.
– Can use a platform‐specific tag in place of a name that
indicates the path should go up a level from the current
location
• Some of the platform‐specific tags are
– ~ Home Directory (of the user logged in)
– / Root Directory (it is different from the directory
named “root”)
– . Current Directory
– .. Parent Directory
Basic Linux
commands
• Observe behavior of the following commands
• [assuming for each execution pwd gives
/home/SysPgm/exercises]
– cd .
– cd ..
– cd /home/SysPgm
– cd /home/SysPgm/dir0
– cd ../dir0
Basic Linux
commands
• Examples of platform specific tags
– [assuming for each execution pwd gives
/home/SysPgm/exercises]
– cd ~/dir0
– cd /home/SysPgm/dir0
– cd ./../dir0
write Command
The write command enables message sending over the system in
real time. It provides conversation-like communication with
another logged-in user. Each user alternately sends and receives
short messages from the other workstation. Long messages can be
sent by putting the complete message in a file and then redirecting
that file as input to the write command.
Ex: To write a message to a user who is logged in,
enter : write username Welcome to Systems Programming
press the Ctrl-D key sequence to terminate the write command mode.
Systems Programming
pwd Command
108
Systems Programming
mkdir - make a directory
Systems Programming
ls command
•Listing Files
•To list the files and directories stored in the current
directory, use the following command
$ ls
Systems Programming
LISTING FILE ATTRIBUTES
Systems Programming
• $ ls –l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02
-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst
-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh
drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs
Systems Programming
ls – l provides attributes like
Systems Programming
5. File size in bytes
6. Last modification time. If you change only the
permissions or ownership of the file, the
modification time remains unchanged
7. Displays file name
Systems Programming
LISTING DIRECTORY ATTRIBUTES
Systems Programming
UNIX files and
directories
•Listing Files: $ ls –
•Prefix & Description
- Regular file, such as an ASCII text file, binary executable, or
hard link.
- b - Block special file. Block input/output device file such as a
physical hard drive.
- c - Character special file. Raw input/output device file such
as a physical hard drive.
- d - Directory file that contains a listing of other files and
directories.
- l - Symbolic link file. Links on any regular file
- p - Named pipe. A mechanism for interprocess communications.
- s - Socket used for interprocess communication.
Systems Programming
UNIX files and
directories
•Metacharacters
•Metacharacters have a special meaning in Unix.
•For example, * and ? are metacharacters.
•We use * to match 0 or more characters, a question mark (?) matches with
a single character.
•$ ls ch*.doc
–Displays all the files, the names of which start with ch and end with .doc −
Systems Programming
UNIX files and
directories
•Hidden Files
•An invisible file is one, the first character of which is the dot or the period
character (.).
•Unix programs (including the shell) use most of these files to store
configuration information.
•Some common examples of the hidden files include the files −
–.profile − The Bourne shell ( sh) initialization script
–.kshrc − The Korn shell ( ksh) initialization script
–.cshrc − The C shell ( csh) initialization script
•To list the invisible files, specify the -a
•$ ls -a
–. .profile docs lib test_results
–.. .rhosts hosts pub users
–.emacs bin hw1 res.01 work
–.exrc ch07 hw2 res.02
Systems Programming
ed command
• ed command in Linux is used for launching the ed text editor which is a line-
based text editor with a minimal interface which makes it less complex for
working on text files i.e creating, editing, displaying and manipulating files. It is
the oldest editor built in the Unix. It is succeeded by vi and emacs text editor.
Syntax: ed [options] [file]
• ed command without any option: It will launch the ed editor with an empty
buffer for us to write, this is similar to the other visual or command line based
editor when invoked without a filename. The simplest way to start the ed text
editor is by typing “ed” into the terminal.
Systems Programming
ed command
• Ex 1: Here we have not specified the filename so this will create an empty buffer
for us to write.
• Ex 2: To Enter into insert mode press “a” and when you are done writing stop it
by “.” (dot).
• Ex 3: To view, the last line enter “p” into the ed command prompt.
• Ex 4: To print all the lines that we inserted in the buffer by using “, p”.
• Ex 5: To save these lines into a file write “f [filename]”.
• Ex 6: Type “w” in ed command prompt to write the data into the file and see how
many bytes are written.
cat : displaying and creating files
cat(concatenate) command is very frequently used in Linux. It
reads data from the file and gives their content as output. It
helps us to create, view, concatenate files.
Systems Programming
frequently used cat
commands.
4) Create a file
$ cat > newfile
Output : Will create a file named newfile
5) Copy the contents of one file to another file.
$cat [source filename] > [destination-filename]
Output : The content will be copied in destination file
6) Cat can append the contents of one file to the end of another file.
$cat file1 >> file2
Output : Will append the contents of one file to the end of another file
7) Cat command can display content in reverse order using tac command.
$tac filenameOutput
Will display content in reverse order
Systems Programming
pr command
• pr displays the specified files on the standard output in
a paginated form, pr formats the given files into single-
column 66-line pages.
• Each page has a 5-line header. A 5-line trailer consists
of blank lines.
• pr command adds suitable headers, footers and
formatted text
• pr adds five lines of margin at the top and bottom
• The header shows the date and time of last
modification of the file along with the filename and page
number
Systems Programming
pr command
pr : paginating files
We know that,
cat dept.lst
01|accounts|6213
02|progs|5423
03|marketing|6521
04|personnel|2365
05|production|9876
06|sales|1006
Systems Programming
pr options
Systems Programming
Basic Linux
commands
• pr can also produce multi‐ column output
– pr ‐3 FirstFile
– pr –J
• merge full lines, no column alignment
– pr –m
• print all files in parallel, one in each column, truncate
lines, but join lines of full length with ‐J
Basic Linux commands
– Exercise #1
• Task #1
– Create two directories SysPgm1 and SysPgm2 under
exercises
• Task #2
– Change directory to SysPgm1 directory
• Task #3
– Create test1 and test2 directories under SysPgm1
directory
• Task #4
– Change directory to SysPgm2 directory using absolute
path
Basic Linux commands
– Exercise #1
• Task #5
– Create test1 directory under SysPgm2 directory
• Task # 6
– From SysPgm2 directory create “check” directory under
SysPgm1 directory
• Task #7
– List the contents of SysPgm1 directory from the current
directory
• Task #8
– Using cd command (only once) to change directory to
dirX directory
Basic Linux commands –
Exercise #1
• Task #9
– Try the following commands and observe the
output obtained.
• ls ~
• ls ../.
• ls ./..
Basic Linux commands –
Exercise #2
• Task #1
– Create directories dir1, dir2, dir3 under exercises.
• Task #2
– Change directory to dir3 directory.
• Task #3
– Display path of current working directory.
• Task #4
– Create test1 directory under dir1 directory from
current working directory.
Basic Linux
commands – Exercise
#2
• Task #5
– Create test2 directory under dir2 directory from current
working directory
• Task #6
– Change directory to test1 directory using relative path
• Task #7
– From test1 directory display contents of dir2 directory
• Task #8
– Change directory to test2 directory by using absolute
path
Basic Linux commands
– Exercise #2
• Task #9
– Try the following commands and observe the
output obtained.
• ls ‐lt
• ls ‐lS
• ls ‐lh
• ls ‐al
The UNIX Pipe (|)
Systems Programming
wc
• wc (word count) simply counts the number of words, lines, and characters in the file(s).
$ wc [-clw] [file1 file2 ... fileN]
• The three parameters, clw, stand for character, line, and word respectively, and tell
wc which of the three to count.
spell
spell is very simple unix spelling program, usually for American English.
spell is a filter, like most of the other programs we’ve talked about.
138
BITS Pilani
cmp
• The first must be listed on command line, while the second is either
listed as the second parameter or is read in form standard input.
•
• cmp is very simple, and merely tells you where the two files first differ.
• $ cmp file1 [ file2]
139
BITS Pilani
diff
• The GNU version of diff has over twenty command line options.
• It is a much more powerful version of cmp and shows you what the differences are
instead of merely telling you where the first one is.
140
BITS Pilani
tr
• The “translate characters” command operates on standard input-it doesn’t accept a
filename as a parameter.
141
BITS Pilani
ed command
• red is a restricted ed: it can only edit files in the current directory and cannot execute
shell commands.
• If invoked with a file argument, then a copy of file is read into the editor’s buffer.
• Changes are made to this copy and not directly to file itself.
• Upon quitting ed, any changes not explicitly saved with a ‘w’ command are lost.
14
2
BITS Pilani
ed command
BITS Pilani
pr command
• Lines consist of text up to and including a newline character.
• Input mode is terminated by entering a single period (.) on a line.
• pr command:
• The pr command is famous for printing a file neatly on a page -- with margins at top
and bottom, filename, date, and page numbers.
• It can also print text in columns: one file per column or many columns for each file.
• The -t option takes away the heading and margins at the top and bottom of each
page. That's useful when "pasting" data into columns with no interruptions.
1
4
4
BITS Pilani
pr command
• The -m option reads all files on the command line simultaneously and prints each in
its own column, like this:
145
BITS Pilani
pr command
• % pr -3 file1
BITS Pilani
pr command
+n starts displaying with the nth page of each file. The default for n is 1.
-n displays n columns of output. This is the obsolete equivalent of -c n.
-a orders input lines across the page on output, instead of down. You should only use this
option with -n.
-c n displays n columns of output. When you specify this option, pr behaves as though
you had also specified the
-e and -i options. When you specify both this option and
-t, pr uses the minimum number of lines possible to display the output. You should not
specify this option with -m.
BITS Pilani
pr command
-e[char][gap] expands each occurrence of the input tab character to a string of spaces
such that the following character has the next column position which is a positive
multiple of gap, plus 1.
BITS Pilani
whi
ch
• Displays a path name of a command.
• Searches a path environmental variable for the command and displays
the absolute path.
• To find which tcsh and bash are actually in use, type:
% which tcsh
% which bash
• % man which for more details
chsh
Course Name :
Systems Programming
163
Systems Programming - V 3.0
What is a file system?
164
Systems Programming - V 3.0
What is a file system?
A file system can refer to the methods and data
structures that an operating system uses to keep track
of files on a disk or partition
• Linux keeps regular files and directories on block
devices such as disks
• A Linux installation may have several physical disk
units, each containing one or more file system types
• Partitioning a disk into several file system instances
makes it easier for administrators to manage the data
stored there
165
Systems Programming - V 3.0
What is a file system?
cylinder
167
Systems Programming - V 3.0
The UNIX File System
• The root directory has many subdirectories. The following table describes some of the
subdirectories contained under root
Directory Content
/bin Common programs, shared by the system, the system administrator and the users.
Contains references to all the CPU peripheral hardware, which are represented as
/dev
files with special properties.
Most important system configuration files are in /etc, this directory contains data
/etc
similar to those in the Control Panel in Windows
/home Home directories of the common users.
Library files, includes files for all kinds of programs needed by the system and the
/lib
users.
/sbin Programs for use by the system and the system administrator.
Temporary space for use by the system, cleaned upon reboot, so don't use this for
/tmp
saving any work!
/usr Programs, libraries, documentation etc. for all user-related programs.
Storage for all variable files and temporary files created by users, such as log files,
/var the mail queue, the print spooler area, space for temporary storage of files.
168
Systems Programming - V 3.0
UNIX and POSIX file attributes
• Inodes
• Structure of a regular file
• Directories
• Conversion of a path name to an inode
• Super block
• Inode assignment to a new file
• Allocation of disk blocks
• Other file types
170
Systems Programming - V 3.0
File System Implementation
(Disk Layout)
Entire Disk
Boot Block
173
Systems Programming - V 3.0
Super Block
Super Block:
- Describes the state of a file system
- How large it is
- How many files it can store
- Where to find free space in the file system
Inode List:
- An inode is the internal representation of a file
contains the description of the disk layout of the file
data
- file owner
- permissions
- The inode list contains all of the inodes present in an
instance of a file system
Data Blocks:
- Contain the file data in the file system
- Additional administrative data
- An allocated data block can belong to one and only
one file in the file system
178
Systems Programming - V 3.0
Inodes in UNIX system
• UNIX system 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 address of file
• Information of a file is accessed using its inode number
• Inode number is unique within a file system
• A file record is identified by a file system ID and inode number
• Inode record doesnot contain the name of the file
• The mapping of filenames to inode number is done via
directory files
179
Systems Programming - V 3.0
What is a file system?
180
Systems Programming - V 3.0
File system consistency check
181
Systems Programming - V 3.0
Kernel I/O structure
182
Systems Programming - V 3.0
I/O in Unix ‐ Devices
183
Systems Programming - V 3.0
I/O in Unix ‐ Devices
184
Systems Programming - V 3.0
I/O in Unix ‐ Devices
185
Systems Programming - V 3.0
File Systems and inodes
186
Systems Programming - V 3.0
File Systems and inodes
187
Systems Programming - V 3.0
Hard Links
188
Systems Programming - V 3.0
ln: Creating Hard Links
189
Systems Programming - V 3.0
WHERE TO USE HARD LINKS
190
Systems Programming - V 3.0
LIMITATIONS OF HARD LINKS
191
Systems Programming - V 3.0
Symbolic Links
192
Systems Programming - V 3.0
Symbolic Links
193
Systems Programming - V 3.0
Contact Session - 4
Course Name :
Systems Programming
195
Systems Programming - V 3.0
Stat command
stat is a command which gives information about
the file and filesystem. Stat command gives
information such as the size of the file, access
permissions and the user ID and group ID, birth
time access time of the file.
196
Systems Programming - V 3.0
Stat command
-L, --dereference follow links
-f, --file-system display file system status instead of
file status
-c --format=FORMAT use the specified FORMAT
instead of the default; output a newline after each
use of FORMAT
197
Systems Programming - V 3.0
Information we get from stat
• File: The file name, If the provided file is a symlink, then the name will be
different.
• Size: The size of a given file in Bytes.
• Blocks: Total number of allocated blocks to the file on hard disk.
• File type: Regular files, special files, directories, or symbolic links.
• Device: Device number in hexadecimal format.
• Inode: Inode number of the file.
• Links: Number of hard links of the file.
• Access: The last time at which the file was accessed.
• Modify: The last time at which file was modified.
• Change: The last time the at which file’s attribute or content was changed.
• Birth: The time at which the file was created.
198
Systems Programming - V 3.0
du Command
du command displays the number of blocks used for files. If
the File parameter specified is actually a directory, all files
within the directory are reported on. If no File parameter
is provided, the du command uses the files in the current
directory.
Notes:
• Files with multiple links are counted and written for only
one entry.
• Block counts are based only on file size
199
Systems Programming - V 3.0
du Command
Flags
-a Displays disk usage for each file specified, or displays the individual
disk usage for each file in a directory.
-k Calculates the block count in 1024-byte units rather than the
default 512-byte units.
-l Allocates blocks evenly among the links for files with multiple links.
By default, a file with two or more links is counted only once.
-s Displays the total disk usage for all specified files, or displays the
total disk usage for all files in a directory.
syntax of du command
du [OPTION]... [FILE]...
200
Systems Programming - V 3.0
df Command
• df command (short for disk filesystem) is used to
show disk utilization for a Linux system.
• Display information of device name, total blocks, total disk space,
used disk space, available disk space and mount points on a file
system
• Display all the file system, use -a option. df –a
• Use -h option to display size in power of 1024 df -h
/home/WASE
• Use -H option to display sizes in power of 1000 df -H
/home/WASE
• Use -T option to display file type df -T
/home/WASE 201
Systems Programming - V 3.0
df Command
To display information about /boot file system,
df /boot
We can display information in various block format. For instance see
1M-byte blocks, run:
df -m
df -m /boot
Show statistics about the number of free and used inodes
Pass the -i as follows to display index node (inodes) info:
df -i
df -i -H
df -i -H -T
202
Systems Programming - V 3.0
Inodes
Each file is represented by a structure, called an inode.
203
Systems Programming - V 3.0
Directories
• Directories are structured in a hierarchical tree. Each
directory can contain files and subdirectories.
207
Systems Programming - V 3.0
I/O in Unix – Block Devices and I/O
208
Systems Programming - V 3.0
I/O in Unix – Block Devices and I/O
209
Systems Programming - V 3.0
File System Algorithms
Every file a UNIX system has a unique inode. Processes interact with files using
well defined system calls. The users specify a file with a character string which is
the file's path and then the system get the inode which is mapped to the file which
corresponds to the path.
210
Systems Programming - V 3.0
inode
211
Systems Programming - V 3.0
inodes
212
inodes
213
Accessing Inodes
The algorithm iget allocates an in-core copy of an inode.
If the inode is not found on a hash queue, it allocates an inode from
the free list and reads the disk copy into the in-core inode.
It already knows the inode number and device number. It calculates
the logical block number on which the disk inode resides according
to how many inodes fit into one disk block.
215
Systems Programming - V 3.0
iput (inode_no) //releaseIncoreInode
– lock inode if not locked
– decrement inode refernece count
– if (refernce count==0)
• if (inode link==0)
– free disk block
– set file type to 0
– free inode
• if (file accessed or inode changed or file changed)
– update disk inode
• put inode on free list
– Release inode lock
216
Systems Programming - V 3.0
Structure of a Regular File
219
Systems Programming - V 3.0
Structure of a regular file
220
Systems Programming - V 3.0
Structure of a regular file
• Processes access data in a file by byte offset and view a file as a
stream of bytes
• The kernel accesses the inode and converts the logical file block
into the appropriate disk block
• algorithm bmap
- The kernel calculates logical block number in file from byte
offset
- The kernel calculates start byte in block for I/O
- The kernel calculates number of bytes to copy to user
- The kernel checks if read-ahead is applicable, then marks inode
- The kernel determines level of indirection
221
Systems Programming - V 3.0
Structure of a regular file
222
Systems Programming - V 3.0
Conversion of Path Name to an Inode
223
Systems Programming - V 3.0
Path conversion to an inode
• if (path name starts with root)
– working inode= root inode
• else
– working inode= current directory inode
• while (there is more path name)
– read next component from input
– read directory content
– if (component matches an entry in directory)
• get inode number for matched component
• release working inode
• working inode=inode of matched component
– else
– return no inode
• return (working inode)
224
Systems Programming - V 3.0
Algorithm namei
- If path name starts from root, then the kernel assigns root
inode(iget) to working inode
- Otherwise, the kernel assigns current directory inode to working
inode
- While there is more path name, the kernel reads next path name
component from input, and verifies that working inode is of
directory, access permissions OK
• If working inode is of root and component is ‘..’, then the
kernel checks whether there is more path name or not
• Otherwise the kernel reads directory by repeated use of
bmap,bread,brelse
225
Systems Programming - V 3.0
Path conversion to an inode
226
Systems Programming - V 3.0
Superblock contents
• size of the file system.
• number of free blocks in the file system.
• list of free blocks in the file system.
• pointer to the next free block in the free blocks list
• size of the inodes list.
• number of free inodes in the file system.
• list of free inodes in the file system.
• pointer to the next free inode in the free inodes list.
• lock fields for the free blocks and free inodes list.
• a field indicating whether the super block has changed.
The kernel periodically writes the superblock to the disk if it had been
modified so that it is consistent with the data on the disk
227
Systems Programming - V 3.0
Inode assignment to a new file
228
Systems Programming - V 3.0
Inode assignment to a new file
229
Systems Programming - V 3.0
Contact Session - 5
Course Name :
Systems Programming
Dr. Parag Anil Tamhankar
Agenda
⮚ The vi basics
⮚ Input mode – entering and replacing text
⮚ Saving text and quitting – the ex mode
⮚ Navigation
⮚ Editing text
⮚ Undoing last editing instructions
⮚ Repeating the last command
⮚ Searching for a pattern
⮚ Substitution – search and replace
⮚ cp, cut, paste commands.
231
Systems Programming - V 3.0
vi basics
• To write and edit some programs and scripts, we require
editors
• UNIX provides vi editor for BSD system – created by Bill
Joy
• Bram Moolenaar improved vi editor and called it as vim
(vi improved) on Linux OS
232
Systems Programming - V 3.0
The vi Editor
The three modes of vi Editor:
1.Command Mode: The default mode of the editor where
every key pressed is interpreted as a command to run on
text. To copy, delete text & navigate, this mode is used.
2.Input Mode: Every key pressed after switching to this
mode actually show up as text. To input text, this mode is
used.
3.ex Mode(Last Line Mode): The mode used to handle
files (like saving) and perform substitution.
233
Systems Programming - V 3.0
The vi Editor
234
Systems Programming - V 3.0
INPUT MODE – ENTERING AND
REPLACING TEXT
235
Systems Programming - V 3.0
INPUT MODE – ENTERING AND
REPLACING TEXT
Insertion of Text (i and a)
236
Systems Programming - V 3.0
INPUT MODE – ENTERING AND REPLACING TEXT
Insertion of Text at Line Extremes (I and A)
237
Systems Programming - V 3.0
INPUT MODE – ENTERING AND REPLACING TEXT
238
Systems Programming - V 3.0
INPUT MODE – ENTERING AND REPLACING
TEXT
Replacing Text (r, s, R and S)
239
Systems Programming - V 3.0
INPUT MODE – ENTERING AND REPLACING
TEXT
Input Mode Commands
240
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Saving the Work (:w)
241
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Saving and Quitting (:x and :wq)
242
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Aborting Editing (:q)
243
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
244
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Writing Selected Lines
245
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Escape to the UNIX Shell (:sh and [Ctrl-z])
246
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Recovering from a Crash (:recover and –r)
247
Systems Programming - V 3.0
ex MODE – SAVING TEXT AND QUITTING
Save and Exit Commands of the ex Mode
248
Systems Programming - V 3.0
Command MODE – NAVIGATION
Movement in the Four Directions (h, j, k and l)
249
Systems Programming - V 3.0
Command MODE – NAVIGATION
Movement in the Four Directions (h, j, k and l)
250
Systems Programming - V 3.0
Command MODE – NAVIGATION
Example
5b takes the cursor 5 words back
3w takes the cursor 3 words forward
251
Systems Programming - V 3.0
Command MODE – NAVIGATION
Moving to Line Extremes (0, | and $)
252
Systems Programming - V 3.0
Command MODE – NAVIGATION
Moving to Line Extremes (0, | and $)
253
Systems Programming - V 3.0
Command MODE – NAVIGATION
Scrolling ([Ctrl-f], [Ctrl-b], [Ctrl-d] and [Ctrl-u])
254
Systems Programming - V 3.0
Command MODE – NAVIGATION
Absolute Movement (G)
255
Systems Programming - V 3.0
Command MODE – EDITING TEXT
Editing Text – Deleting characters (x, X)
256
Systems Programming - V 3.0
Command MODE – EDITING TEXT
Editing Text – Deleting lines (dd)
257
Systems Programming - V 3.0
Command MODE – EDITING TEXT
Editing Text – Moving Text (p, P)
258
Systems Programming - V 3.0
Command MODE – EDITING TEXT
Editing Text)
259
Systems Programming - V 3.0
Command MODE – EDITING TEXT
260
Systems Programming - V 3.0
Command MODE – EDITING TEXT
Editing Text – Joining Lines (J)
261
Systems Programming - V 3.0
Command MODE – EDITING TEXT
262
Systems Programming - V 3.0
Command MODE – EDITING TEXT
263
Systems Programming - V 3.0
SEARCHING FOR A PATTERN
• / search forward
• ? search backward
264
Systems Programming - V 3.0
Command MODE – EDITING TEXT
265
Systems Programming - V 3.0
ex MODE
Substitution – Search and Replace ( :s )
266
Systems Programming - V 3.0
ex MODE
268
Systems Programming - V 3.0
ex MODE
Command Function
:nd Deletes nth line
:m,n d Deletes line from m to n
:n mo p Moves line n after line p
:m,n mo p Moves line m to n after line p
:m co p Copies line m after line p
:m,n co p copies line m to n after line p
:m,n w file1 writes line m to n to a file file1
:m,n w >>file1 Appends line m to n to file file1
:r file1 Reads the contents of the file file1 at
current cursor position
:r !command Executes shell command and the
output of the command is read at the
current cursor position.
269
Systems Programming - V 3.0
cp – COPYING A FILE
270
Systems Programming - V 3.0
cp – COPYING A FILE
271
Systems Programming - V 3.0
cp – COPYING A FILE
272
Systems Programming - V 3.0
File Management Commands
274
Systems Programming - V 3.0
cut Command
275
Systems Programming - V 3.0
cut Command
276
Systems Programming - V 3.0
paste Command
277
Systems Programming - V 3.0
paste: pasting file (contd.,)
278
Systems Programming - V 3.0
paste Command
279
Systems Programming - V 3.0
Contact Session - 6
Course Name :
Systems Programming
Dr. Parag Tamhankar
Agenda
⮚ Commands :
• cat - to create, view, concatenate files.
• mv - mv is used to move one or more files or directories
• rm - removes the entries for a specified file, group of files.
• cmp, comm, diff - to display the differences by comparing the files
• chmod- used to change the access permissions
• top - Displays list of running processes
• head- Pick lines from the beginning
• tail - Pick lines from the end
• sort - Sort, merge and remove
• wc - to find number of lines, word count, byte and characters.
• tee - to view output and at the same time store it in a file
281
Systems Programming - V 3.0
cat – DISPLAYING AND CREATING FILES
282
Systems Programming - V 3.0
cat – DISPLAYING AND CREATING FILES
283
Systems Programming - V 3.0
cat – DISPLAYING AND CREATING FILES
284
Systems Programming - V 3.0
rm – DELETING FILES
285
Systems Programming - V 3.0
rm – DELETING FILES
286
Systems Programming - V 3.0
rm – DELETING FILES
287
Systems Programming - V 3.0
rm – DELETING FILES
288
Systems Programming - V 3.0
mv – RENAMING FILES
289
Systems Programming - V 3.0
cmp – COMPARING TWO FILES
290
Systems Programming - V 3.0
comm – WHAT IS COMMON?
291
Systems Programming - V 3.0
comm – WHAT IS COMMON?
292
Systems Programming - V 3.0
comm – WHAT IS COMMON?
293
Systems Programming - V 3.0
diff – CONVERTING ONE FILE TO OTHER
294
Systems Programming - V 3.0
umask: DEFAULT FILE AND DIRECTORY
PERMISSIONS
• Usually we have,
rw-rw-rw- (octal 666) for regular files
rwxrwxrwx (octal 777) for directories
• The default is transformed by subtracting the user
mask from it to remove one or more permissions
• We can evaluate the current value of the mask as,
$ umask
022
295
Systems Programming - V 3.0
FILE OWNERSHIP
296
Systems Programming - V 3.0
FILE OWNERSHIP
298
Systems Programming - V 3.0
RELATIVE AND ABSOLUTE
PERMISSIONS
299
Systems Programming - V 3.0
RELATIVE PERMISSIONS
300
Systems Programming - V 3.0
RELATIVE PERMISSIONS
301
Systems Programming - V 3.0
RELATIVE PERMISSIONS
302
Systems Programming - V 3.0
RELATIVE PERMISSIONS
• Examples
-rw-r--r-- 1 kumar metal 1906 sep 23:38
xstart
Let initially
Then, it becomes
-rwx--x--x 1 kumar metal 1906 sep 23:38 xstart
305
Systems Programming - V 3.0
ABSOLUTE PERMISSIONS
306
Systems Programming - V 3.0
ABSOLUTE PERMISSIONS
309
Systems Programming - V 3.0
PERMISSIONS
310
Systems Programming - V 3.0
THE SECURITY IMPLICATIONS
311
Systems Programming - V 3.0
chmod RECURSIVELY
312
Systems Programming - V 3.0
DIRECTORY PERMISSIONS
313
Systems Programming - V 3.0
DIRECTORY PERMISSIONS
314
Systems Programming - V 3.0
CHANGING FILE OWNERSHIP
315
Systems Programming - V 3.0
chown Command
316
Systems Programming - V 3.0
chgrp Command
ls –l dept.lst
we can also specify a character position with in a field to be the beginning of sort
as shown above (sorting on columns).
319
Systems Programming - V 3.0
head - display the start of a file
Examples
By default head displays the first 10 lines. You can display more with the "-n
number", or "-number" options, e.g., to display the first 40 lines:
head -40 filename or head -n 40 filename
320
Systems Programming - V 3.0
tail - display the end of a file
tail displays the tail, or end, of the file.
Syntax
tail [options] file
Common Options
-number number of lines to display, counting from the bottom of
the file
Examples
The default is to display the last 10 lines, but you can specify
different line or byte numbers, or a different starting point within
the file. To display the last 30 lines of a file use the -number
style:
tail -30 filename
321
Systems Programming - V 3.0
wc – COUNTING LINES, WORDS AND
CHARACTERS
322
Systems Programming - V 3.0
wc – COUNTING LINES, WORDS AND
CHARACTERS
323
Systems Programming - V 3.0
wc – COUNTING LINES, WORDS AND
CHARACTERS
324
Systems Programming - V 3.0
Tee Command
Tee command is used to store and view (both at the same time)
the output of any other command.
Tee command writes to the STDOUT, and to a file at a time as
shown in the examples below
The following command writes the output only to the file and not
to the screen.
$ ls > file
SYNOPSIS
top [-] [d delay] [p pid] [q] [c] [C] [S] [s] [i] [n iter] [b] DESCRIPTION
top provides an ongoing look at processor activity in real time.
It displays a listing of the most CPU-intensive tasks on the system, and
can provide an interactive interface for manipulating processes.
It can sort the tasks by CPU usage, memory usage and runtime. can be
better configured than the standard top from the procps suite.
326
Systems Programming - V 3.0
Contact Session - 7
Course Name :
Systems Programming
329
grep Command
330
grep Command
331
emp.lst (Data used for grep)
• 2233 | a.k.shukla | g.m | sales | 12/12/52 | 6000
• 9876 | jai sharma | director | production | 12/03/50 | 7000
• 5678 | sumit chakrobarty | d.g.m. | marketing | 19/04/43 | 6000
• 2365 | barun sengupta | director | personnel | 11/05/47 | 7800
• 5423 | n.k.gupta | chairman | admin | 30/08/56 | 5400
• 1006 | chanchal singhvi | director | sales | 03/09/38 | 6700
• 6213 | karuna ganguly | g.m. | accounts | 05/06/62 | 6300
• 1265 | s.n. dasgupta | manager | sales | 12/09/63 | 5600
• 4290 | jayant choudhury | executive | production | 07/09/50 | 6000
• 2476 | anil aggarwal | manager | sales | 01/05/59 | 5000
• 6521 | lalit chowdury | directir | marketing | 26/09/45 | 8200
• 3212 | shyam saksena | d.g.m. | accounts | 12/12/55 | 6000
• 3564 | sudhir agarwal | executive | personnel | 06/07/47 | 7500
• 2345 | j. b. sexena | g.m. | marketing | 12/03/45 | 8000
• 0110 | v.k.agrawal | g.m.| marketing | 31/12/40 | 9000
332
grep Command
334
grep frequently used options
335
grep Command
336
grep Command
337
grep Command
338
BASIC REGULAR EXPRESSIONS
339
BRE character subset
340
The character class
341
grep Command
342
THE *
343
THE DOT
344
^ and $
345
grep Command
347
EXTENDED RE (ERE)
348
grep ERE
349
The ERE set
350
Matching multiple patterns
351
Essential Shell programming
352
What is Shell?
• A Shell Is a program that interprets commands
• It allows a user to execute commands
• Either manually at a terminal or
automatically in programs called shell scripts
• A shell is not an operating system
• It is a way to interface with the operating
system and execute commands
• Login shell is BASH = Bourne Again Shell
353
Advantage of using Shell
1. File name short hands
– Can pick up a whole set of file names as arguments to
a program by specifying a pattern for the names
– Shell will find all the filenames that match the pattern
2. Input – Output redirection
– Can take input from a file and can redirect output to a
file
3. Personalizing the environment
– Can define own commands and short hands
354
Bash
Shell provides a mechanism for generating a list
of file names that match a pattern
– Example: ls ‐l *.c
– All file names in the current directory that end in .c
– The character * is a pattern that will match any string
including the null string
– This mechanism is useful both to save typing and to
select names according to some pattern
355
Wild cards
Wild cards – Special characters interpreted by shell
356
Wild card – “*”
357
Shell Meta characters
358
Shell Meta characters
359
Shell Scripts
The shell may be used to read and execute
commands contained in a file
• Assume a scenario where commands who, ls and
date are executed one after the other
• To write a shell script to achieve this:
– Open a new file [say firstShellPgm.sh] in vi editor
– Type all the commands that you want to get
executed one after the other. i.e. who, ls and date
– Save the file using :wq option.
360
Wild card – “?”
361
Examples
362
System Variables in Shell
363
What is Shell Programming
364
Need for Shell Programming
365
Shell Scripts/Shell Programs
366
Shell Scripts
Example: script.sh
#! /bin/sh
# script.sh: Sample Shell Script
echo “Welcome to Shell Programming”
echo “Today’s date : `date`”
echo “This months calendar:”
cal `date “+%m 20%y”` This month’s calendar.
367
Shell Scripts
368
Shell Scripts
369
Read: Making Scripts Interactive
370
Read: Making Scripts Interactive
371
Using Command Line Arguments
372
Using Command Line Arguments
373
Using Command Line Arguments
#! /bin/sh
echo “Program Name : $0”
echo “No of Arguments : $#”
echo “Arguments are : $*”
$ chmod +x 2.sh
$ 2.sh A B C
o/p Program Name : 2.sh
No of Arguments : 3
Arguments are : A B C
374
Contact Session - 9
Course Name :
Systems Programming
Shell Scripting
Agenda
376
Systems Programming - V 3.0
Shell Scripts/Shell Programs
377
Systems Programming - V 3.0
Using Command Line Arguments
378
Systems Programming - V 3.0
Using Command Line Arguments
379
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
echo "Hello, Student”
# This prompts the user for input, assigns this to the variable name and
then displays the value of this variable to standard output.
# If there is more than one word in the input, each word can be assigned
to a different variable.
# Any words left over are assigned to the last named variable.
echo -e "\nPlease enter your surname\n"
echo -e "Followed by your first name: \c"
read name1 name2
echo -e "\nWelcome to Wipro $name2 $name1“
381
Systems Programming - V 3.0
Shell Scripts
# Script to print user information who currently login , current date & time
#
clear
echo -e "\nHello $USER"
echo -e "\nToday is \c ";date
echo -e "\nNumber of user login : \c" ; who | wc -l
echo -e "\nCalendar\n"
cal
382
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
# Script that demos, command line args
echo "Total number of command line argument are $#"
echo "$0 is script name"
echo "$1 is first argument"
echo "$2 is second argument"
echo "All of them are :- $* "
383
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
# Script that demos, command line args
echo "Total number of command line argument are $#"
echo "$0 is script name"
echo "$1 is first argument"
echo "$2 is second argument"
echo "All of them are :- $* "
384
Systems Programming - V 3.0
Starting
#!/bin/sh
# This is a comment!
echo Hello World # This is a comment, too!
#var.sh
#!/bin/sh
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
• MY_MESSAGE is a variable
• echo is used to echo the value on console
• $ sign is used to signify a variable
# var1.sh
#!/bin/sh
echo What is your name?
read MY_NAME
echo "Hello $MY_NAME - hope you're well."
• MY_NAME is a variable
• read helps to read the value from console
• echo is used to echo the value on console
• $ sign is used to signify a variable
# myvar2.sh
#!/bin/sh
echo "MYVAR is: $MYVAR"
MYVAR="hi there"
echo "MYVAR is: $MYVAR"
Output:
$ ./myvar2.sh
MYVAR is:
MYVAR is: hi there
Note: MYVAR hasn't been set to any value, so it's blank.
$ MYVAR=hello
$ ./myvar2.sh
MYVAR is:
MYVAR is: hi there
• Note: When you call myvar2.sh from your interactive shell, a new
shell is spawned to run the script.
$ export MYVAR
$ ./myvar2.sh
MYVAR is: hello
MYVAR is: hi there
• Note: We need to export the variable for it to be inherited by another
program - including a shell script.
• But changing the value does not export it back.
$ MYVAR=hello
$ echo $MYVAR
hello
$ . ./myvar2.sh
MYVAR is: hello
MYVAR is: hi there
$ echo $MYVAR
hi there
# var3.sh
#!/bin/sh
echo "What is your name?"
read USER_NAME
echo "Hello $USER_NAME"
echo "I will create you a file called ${USER_NAME}_file"
touch "${USER_NAME}_file"
C programs and Shell Scripts have the same command ( function in C) to terminate
the process. exit in Shell and exit() in C.
Normally success does not need to be explicitly stated but the exit condition for
failure is often used explicitly.
Example if a grep command does not find a pattern the exit function with a non-zero
argument is invoked exit(1) command may be used.
$ cat foo
cat: can’t open foo
Returns a nonzero exit status because it could not open the file. The sheel offers a
variable ($?) and a command (test) that evaluates a command exit status.
397
Systems Programming - V 3.0
exit and Exit Status of Command
3 These returns conditions are used by programmers to control the flow of the
program.
398
Systems Programming - V 3.0
The Logical Operators && and ||- Conditional
Execution
Shell provides two operators that allow conditional execution - && and || as follows:
The && delimits two commands: cmd2 is executed only when cmd1 succeeds.
Example:
$ grep ‘director’ emp.lst && echo “Pattern found in file”
399
Systems Programming - V 3.0
The Logical Operators && and ||- Conditional
Execution
The || delimits two commands: cmd2 is executed only when cmd1 fails.
Example:
$ grep ‘manager’ emp.lst || echo “Pattern not found”
Pattern not found
You have seen the for simple decision you can use && and ||. If statements need to be
considered only for more complex decisions.
400
Systems Programming - V 3.0
The if Conditional
401
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
#Script to print file
if cat $1
then
echo -e "\n\nFile $1, found and successfully
echo ed“
fi
#!/bin/bash
# Script to see whether argument is positive
if test $1 -ge 0
then
echo "$1 number is positive“
fi 402
Systems Programming - V 3.0
The if Conditional
403
Systems Programming - V 3.0
Using test and [] to evaluate expressions
404
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
405
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
406
Systems Programming - V 3.0
Shell Scripts
# very simple 'if'
#!/bin/bash
echo 'Enter a number '
read x
if [ $x -eq 10 ]
then
echo "Entered value is 10"
fi #!/bin/bash
echo 'Enter a number'
read x
if [ $x -eq 10 ]
then
echo "Entered value is 10"
else
echo "Entered value is not 10"
fi
407
Systems Programming - V 3.0
Shell Script
#!/bin/bash
echo 'Enter a number'
read x
if [ $x -eq 10 ]
then
echo "Entered value is 10"
elif [ $x -eq 100 ]
then
echo "Entered value is 100"
else
echo "Entered value is not 10 and not 100"
fi 408
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
echo -n 'Enter a number'
read x
if [ $x -gt 10 ]
then
if [ $x -lt 100 ]
then
echo "Entered value is greatedthan 10 and lessthan 100"
fi
fi
409
Systems Programming - V 3.0
Shell Scripts
#!/bin/bash
# Script to see whether argument is positive
if test $1 -gt 0
then
echo "$1 number is positive"
fi
if rm $1
then
echo "$1 file deleted"
fi
410
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
411
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
412
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
413
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
414
Systems Programming - V 3.0
Using test and [] to evaluate expressions –
Numeric Comparison
415
Systems Programming - V 3.0
The case Conditional
416
Systems Programming - V 3.0
The case Conditional
417
Systems Programming - V 3.0
The case Conditional – Matching Multiple Patterns
418
Systems Programming - V 3.0
The case Conditional – Wild-Cards
419
Systems Programming - V 3.0
expr – Computation and String handling
420
Systems Programming - V 3.0
expr – Computation
421
Systems Programming - V 3.0
expr – Computation
422
Systems Programming - V 3.0
expr – String Handling
423
Systems Programming - V 3.0
expr – String Handling
424
Systems Programming - V 3.0
expr – String Handling
425
Systems Programming - V 3.0
QUIZ
a) Continuing...
b) Stopping...
c) Invalid input
d) Syntax error
Answer : a
428
Which of the following correctly tests if a number stored in var
is either greater than 100 or less than 10?
429
What is the output of the following script if x=5 and y=10?
430
Scenario
You need to write a shell script that performs different operations
on a file based on its attributes. The script should
Check if the file exists. If not, create it.
If the file is empty, write "This is a new file" to it.
If the file is not empty, append the current date and time to the
file.
Finally, display the contents of the file.
Task
Implement the script using decision-making constructs.
Consider edge cases, such as incorrect file paths or permission
issues.
431
ANSWER
#!/bin/bash
file="example.txt"
if [ ! -e "$file" ]; then
echo "File does not exist. Creating $file..."
touch "$file"
fi
if [ ! -s "$file" ]; then
echo "This is a new file" > "$file"
echo "Added text to new file."
else
echo "File is not empty. Appending date and time..."
echo "$(date)" >> "$file"
fi
echo "Displaying contents of $file:"
cat "$file"
432
Contact Session - 10
Course Name :
Systems Programming
Agenda
434
Systems Programming - V 3.0
while: Looping
435
Systems Programming - V 3.0
while: Looping – Setting up an Infinite loop
436
Systems Programming - V 3.0
while: Looping
437
Systems Programming - V 3.0
while: Looping
438
Systems Programming - V 3.0
while: Looping
439
Systems Programming - V 3.0
while: Looping
440
Systems Programming - V 3.0
while: Looping
441
Systems Programming - V 3.0
Print numbers as 5,4,3,2,1
using while loop
#!/bin/bash
i=5
while test $i != 0
do O/P
5
echo "$i" 4
i=`expr $i - 1` 3
2
done 1
442
Systems Programming - V 3.0
Tables Printing using while loop
if [ $# -eq 0 ]
then
echo "Wrong number of arguments from command line"
exit 1 sh filename.sh 5
fi O/P
n=$1 5*1=5
5 * 2 = 10
i=1 5 * 3 = 15
while [ $i -le 10 ] 5 * 4 = 20
do 5 * 5 = 25
5 * 6 = 30
echo "$n * $i = `expr $i \* $n`" 5 * 7 = 35
i=`expr $i + 1` 5 * 8 = 40
done 5 * 9 = 45
5 * 10 = 50
443
Systems Programming - V 3.0
Pyramid printing using while
*
***
*****
*******
*********
444
Systems Programming - V 3.0
Shell script to find sum of first N numbers
from number M (take N and M from the user)
445
Systems Programming - V 3.0
for: Looping with a list
446
Systems Programming - V 3.0
for: Looping with a list
447
Systems Programming - V 3.0
for: Looping with a list –
Possible sources of the List
448
Systems Programming - V 3.0
for: Looping with a list –
Possible sources of the List
449
Systems Programming - V 3.0
Program to break out of a for loop using
'break' command as shown below
clear
i=1
for day in Mon Tue Wed Thu Fri
do
echo "Weekday $((i++)) : $day"
if [ $i -eq 3 ]; then
break;
fi
done
O/P:
Weekday 1 : Mon
Weekday 2 : Tue
450
Systems Programming - V 3.0
Program to add "(WEEKEND)" to Sat and
Sun, and "(weekday)" to rest of the days.
clear
i=1
for day in Mon Tue Wed Thu Fri Sat Sun
do
echo -n "Day $((i++)) : $day"
if [ $i -eq 7 -o $i -eq 8 ]; then O/P
Day 1 : Mon (weekday)
echo " (WEEKEND)" Day 2 : Tue (weekday)
Day 3 : Wed (weekday)
continue; Day 4 : Thu (weekday)
fi Day 5 : Fri (weekday)
Day 6 : Sat (WEEKEND)
echo " (weekday)" Day 7 : Sun (WEEKEND)
done
451
Systems Programming - V 3.0
Program to sum the numbers
passed to its argument on command line
clear
if [ $# -eq 0 ]
then
echo "No arguments passed"
exit
fi
sum=0
for i in $*
do
sum=`expr $sum + $i` O/P
sh filename.sh 20 30 40 10 50
done Sum of Numbers is : 150
echo "Sum of Numbers is : $sum"
452
Systems Programming - V 3.0
Pyramid printing using for loop
rows=5
454
Systems Programming - V 3.0
Program to find factorial of a positive
integer N (take N from the user). fact(N)=1×2×…..×N
for loop
O/P
echo "Input N" fi Input N
read N for ((i=0; i<N; i++)) 5
0
fib0=0 do 1
fib1=1 echo "$fib0 " 1
fib2=1 fib0=$fib1 2
3
if [ $N -lt 0 ] fib1=$fib2
then fib2=`expr $fib0 + $fib1`
echo "Wrong arg" done
exit 1
456
Systems Programming - V 3.0
Nesting of Loops [for and while]
457
Systems Programming - V 3.0
Nesting of Outer Loop and Inner Loop
1,1
1,2
i=1 1,3
while [ $i -le 4 ] # Outer for loop 1,4
do
j=1 2,1
while [ $j -le 4] # Inner for loop 2,2
do 2,3
echo "$i , $j " 2,4
j=`expr $j + 1`
3,1
done
3,2
echo " " #print the new line 3,3
i=`expr $i + 1` 3,4
done
4,1
4,2
4,3
4,4 458
Systems Programming - V 3.0
Nesting of Loops [for and while]
459
Systems Programming - V 3.0
Take two integer numbers N and M from user and
display all the Multiplication table between N and M
460
Systems Programming - V 3.0
Take start range as N and end range as M from user and
Find all prime numbers between N and M
461
Systems Programming - V 3.0
Files in Shell Scripting
In shell programming, files are fundamental for storing and
manipulating data. Below are some key file concepts in shell
programming:
1. File Types
Regular Files: These are standard files that contain data, such as
text files, binaries, etc.
Directories: These contain information about files and other
directories.
Special Files: These include devices, pipes, and sockets.
462
Systems Programming - V 3.0
Files in Shell Scripting
2. File Operations
Reading Files: Using commands like cat, less, more, head, tail, or by
opening them in a loop with read.
Writing to Files: Using redirection (> or >>) or commands like echo,
tee.
Appending to Files: Using >> to add content to the end of a file
without overwriting it.
Deleting Files: Using the rm command to remove files.
Copying Files: Using cp to duplicate files.
Moving/Renaming Files: Using mv to move or rename files.
Creating Files: Using touch to create an empty file or
echo "" > filename to create and write to a file.
463
Systems Programming - V 3.0
Files in Shell Scripting
3. File Redirection
Task
• Copy numLine number of lines from the
starting line number startNum of the file
named data.txt
• Store the copied lines in a file named
datanew.txt
• Take numLine and startNum as user input
466
Systems Programming - V 3.0
Files using Shell Scripting
Method I
467
Systems Programming - V 3.0
Files using Shell Scripting
468
Systems Programming - V 3.0
Copy the odd lines of the file named data.txt to a
file named odd.txt and copy the even lines of the
file named even.txt
i=1
while read line
do
if [ `expr $i % 2` ‐eq 0 ]
then
echo $line >> even.txt
else
echo $line >> odd.txt
fi
i=`expr $i + 1`
done<integernos.txt 469
Systems Programming - V 3.0
Write a shell script to find all
prime numbers from integernos.txt file and
store in another file called primes.txt
470
Systems Programming - V 3.0
Shell script that reads numbers from a file, checks which ones
are prime, and writes the prime numbers to another file
# Read numbers from the input file and check for primes
while read -r number; do
if is_prime "$number"; then
echo "$number" >> "$output_file"
fi
done < "$input_file"
472
Systems Programming - V 3.0
set and shift: Manipulating the Positional
Parameters
473
Systems Programming - V 3.0
set and shift: Manipulating the Positional
Parameters
474
Systems Programming - V 3.0
shift: Shifting Arguments left
475
Systems Programming - V 3.0
Contact Session - 11
Course Name :
Systems Programming
awk
getopts
automation using shell
crontab
at command for scheduling
477
Systems Programming - V 3.0
awk
awk is a powerful text-processing tool in
Unix/Linux. It is used for pattern scanning and
processing.
Example 1: Print specific columns
Suppose you have a file sp.txt with the following
content:
A Gautam 25 Developer
Chandrashekhar 30 Manager
Rajeev 22 Designer
478
Systems Programming - V 3.0
awk
Example 1: You want to print the names and their
job titles:
O/P:
A Gautam Developer
Chandrashekhar Manager
Rajeev Designer 479
Systems Programming - V 3.0
awk
Example 2: Sum of column
If you have a file system.txt consists of following
numbers: 10,20,30,40
To calculate the sum of the numbers:
awk '{s+=$1} END {print s}' system.txt
O/P:
100
480
Systems Programming - V 3.0
getopts
getopts is a built-in shell function used to parse
command-line options. Here is example f1.sh
#!/bin/bash
while getopts "a:b:c" opt; do
case $opt in
a) echo "Option a with value: $OPTARG" ;;
b) echo "Option b with value: $OPTARG" ;;
c) echo "Option c selected" ;;
\?) echo "Invalid option: -$OPTARG" ;;
esac
done
481
Systems Programming - V 3.0
getopts
getopts: This built-in command is used to parse command-line
options. It reads options and their arguments, one by one, from
the command line.
The while loop will continue to process options until all options
from the command line are parsed.
Systems Programming 482
getopts
Execute the following command
./f1.sh -a 10 -b 20 –c
O/P:
Option a with value: 10
Option b with value: 20
Option c selected
483
Systems Programming - V 3.0
Automation Using Shell
Automation often involves combining shell
scripts with other tools like awk, sed, etc.
Example 1: Automated Backup Script
#!/bin/bash
# Backup Directory
BACKUP_DIR="/backup"
# Create Backup with Timestamp
tar -czf $BACKUP_DIR/backup_$(date +%F_%T).tar.gz /path/to/data
# Print Message
echo "Backup created at $BACKUP_DIR"
484
Systems Programming - V 3.0
Automation Using Shell
BACKUP_DIR="/backup": This line defines the path to
the directory where the backup will be stored. The
variable BACKUP_DIR holds this path. You can change
/backup to any directory where you want to save the
backup.
487
Systems Programming - V 3.0
crontab
Example 2: Run a Command Every 5 Minutes
*/5 * * * * /path/to/command
• */5: This means "every 5 minutes." The */
syntax specifies that the command should run
at every interval of 5 minutes.
• *: The remaining asterisks represent "every
hour," "every day," "every month," and "every
day of the week," respectively.
488
Systems Programming - V 3.0
at
at is used to schedule a command to run
once at a particular time.
Example 1: Run a Command at 3:30 PM
echo "tar -czf /backup/backup.tar.gz
/path/to/data" | at 3:30 PM
• echo "tar -czf /backup/backup.tar.gz /path/to/data":
This echoes the command that you want to execute at the
scheduled time.
• | at 3:30 PM: The at command schedules the echoed
command to run at 3:30 PM on the current day.
489
Systems Programming - V 3.0
Advanced Example
You can combine all these tools to create an
automated system monitoring script that runs
periodically and alerts you if something goes
wrong.
490
Systems Programming - V 3.0
Advanced Example: monitor.sh
#!/bin/bash
# Check Disk Usage
DISK_USAGE=$(df / | grep / | awk '{print $5}' | sed 's/%//g')
# Threshold
THRESHOLD=90
# If Disk Usage Exceeds Threshold, Send an Email
if [ $DISK_USAGE -gt $THRESHOLD ]; then
echo "Disk usage is critically high: $DISK_USAGE%" | mail -s "Disk
Usage Alert" chandrashekhar.chavan@wilp.bits-pilani.ac.in
Fi
crontab Entry: */30 * * * * /path/to/monitor.sh
491
Systems Programming - V 3.0
Advanced Example: monitor.sh
df /: The df command reports the disk space usage of
file systems. df / checks the root ("/") file system.
grep /: Filters the output to include only the line
containing the root file system.
awk '{print $5}': Extracts the fifth column, which
represents the percentage of disk space used.
sed 's/%//g': Removes the percentage symbol (%) from
the value so that it can be compared as an integer.
492
Systems Programming - V 3.0
Advanced Example: monitor.sh
echo "Disk usage is critically high: $DISK_USAGE%": Prepares the
message body, including the current disk usage percentage.
*/30 * * * *: This crontab entry means the script will run every 30
minutes.
Script 1
Script to read values from the user and perform arithmetic operations
#!/bin/bash
##Arithmetic operations using inputs read from the user
echo "Enter the values : "
read -p 'Enter Value 1: ' a
read -p 'Enter Value 2: ' b
ADD=$(($a+$b))
SUB=$(($a-$b))
MUL=$(($a*$b))
DIV=$(($a/$b))
echo -e "Addition=$ADD\nSubtraction=$SUB\nMultiplication=$MUL\nDivision=$DIV"
Script for arithmetic operations using case
statement
Script 2
#!/bin/bash
###Arithmetic Operations using case statement
read -p 'Enter Value1 : ' a
read -p 'Enter value2 : ' b
read -p 'Enter the operation[ADD|SUB|MUL|DIV]: ' op
case $op in
ADD) ADD=$(($a+$b))
echo "Addition = $ADD" ;;
SUB) SUB=$(($a-$b))
echo "Subtraction = $SUB" ;;
MUL) MUL=$(($a*$b))
echo "Multiplication = $MUL" ;;
DIV) DIV=$(($a/$b))
echo "Divide = $DIV" ;;
*) echo "Invalid Operation!!" ;;
esac
Script 3
Script to demonstrate the useage of Array
Variables
if – statement
###Script to check the type of file
#!/bin/bash
###File test using if--else statement
FILE='/dev/sda'
if [ -c $FILE ]; then
echo "$FILE is a character special file"
else
echo "$FILE is not a character special file"
fi
if [ -b $FILE ]; then
echo "$FILE is a block special file"
else
echo "$FILE is not a block special file"
fi
if [ -d $FILE ]; then
echo "$FILE is a directory"
else
echo "$FILE is not a directory"
fi
Script 5
#!/bin/bash
# Counting the number of lines in a list of files
# for loop over arguments
if [ $# -lt 1 ]
then
echo "Usage: $0 file ..."
exit 1
fi
echo "$0 counts the lines of code"
l=0
n=0
s=0
for f in $*
do
l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
echo "$f: $l"
n=$[ $n + 1 ]
s=$[ $s + $l ]
Done
echo "$n files in total, with $s lines in total"
Contact Session - 12
Course Name :
Systems Programming
System calls
System calls for Process management
Execution of system calls
501
Systems Programming - V 3.0
System Call
502
Systems Programming - V 3.0
System calls for low level I/O
503
Systems Programming - V 3.0
File related system calls ‐ open
504
Systems Programming - V 3.0
File related system calls – creat, close
505
Systems Programming - V 3.0
File related system calls – read
506
Systems Programming - V 3.0
File related system calls – write
507
Systems Programming - V 3.0
System call program example
508
Systems Programming - V 3.0
File related system calls – lseek
509
Systems Programming - V 3.0
File related system calls – lseek
510
Systems Programming - V 3.0
File related system calls – mkdir, rmdir
511
Systems Programming - V 3.0
File related system calls – rename
512
Systems Programming - V 3.0
File related system calls – link
513
Systems Programming - V 3.0
File related system calls – symlink
514
Systems Programming - V 3.0
File related system calls – unlink
515
Systems Programming - V 3.0
System calls related to process
fork :- For creating a duplicate process from the parent
process.
wait :- Processes are supposed to wait for other processes to
complete their work.
exec :- Loads the selected program into the memory.
exit :- Terminates the process
signal :- signal() system call installs a new signal handler for the
signal with number signum.
kill :- Takes two arguments. The first, pid, is the process ID you
want to send a signal to, and the second, sig, is the signal you
want to send. Therefore, you have to find some way to know the
process ID of the other party.
raise :- The raise() function sends the signal sig to the running
program.
516
Process related system calls – fork
517
Systems Programming - V 3.0
Process related system calls – fork
518
Systems Programming - V 3.0
Process related system calls – fork
519
Systems Programming - V 3.0
Calling fork()
Calling fork()
Consider the following example in which we have used the fork() system call to create
a new child process:
int main()
{
fork();
fork(); Now the total number of process
created are 24 = 16 and we have our
fork();
print statement executed 16 times.
fork();
printf("Using fork() system call\n");
return 0;
}
521
Systems Programming - V 3.0
Calling fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t p;
p = fork();
if(p==-1) {
printf("There is an error while calling fork()\n");
}
if(p==0){
printf("We are in the child process\n"); OUTPUT:
} sysads@linuxhint $ gcc fork.c -o fork
else { sysads@linuxhint $ ./fork
printf("We are in the parent process\n"); We are in the parent process
} We are in the child process
return 0;
} 522
Systems Programming - V 3.0
Calling fork()
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h> Output:
//main function begins This is the parent process
int main()
{ This is the child process
pid_t p= fork(); //calling of fork system call
if(p==-1)
printf("Error occured while calling fork()");
else if(p==0)
printf("This is the child process");
else
printf("This is the parent process");
return 0;
}
523
Systems Programming - V 3.0
Process Creation Example
524
Systems Programming - V 3.0
Process related system calls – wait
525
Systems Programming - V 3.0
Process related system calls – wait
526
Systems Programming - V 3.0
Process related system calls – wait
527
Systems Programming - V 3.0
Process related system calls – wait
#include<stdio.h> [vasudevarao@localhost Systemcalls]$ gcc
#include<sys/wait.h> Wait1.c -o Wait1
#include<unistd.h> [vasudevarao@localhost Systemcalls]$ ./Wait1
Hello from parent
int main(){ Hello from child
if (fork()== 0) Bye
printf("HC: hello from child\n"); Child has terminated
Bye
else {
printf("HP: hello from parent\n");
wait(NULL);
printf("CT: child has terminated\n");
}
printf("Bye\n");
return 0;
} 528
Systems Programming - V 3.0
Process related system calls – wait
529
Systems Programming - V 3.0
Output of system calls – wait
[vasudevarao@localhost Systemcalls]$ gcc Wait.c -o Wait
[vasudevarao@localhost Systemcalls]$ ./Wait
fork program starting
This is from parent process
This is from child process I am exiting
Child exited already now with exit status 512
530
Systems Programming - V 3.0
Process related system calls – exec
531
Systems Programming - V 3.0
Process related system calls – exec
532
Systems Programming - V 3.0
Working of exec
• Current process image is overwritten with a new process
image.
• New process image is the one you passed as exec argument
• The currently running process is ended
• New process image has same process ID, same environment,
and same file descriptor (because process is not replaced
process image is replaced)
• The CPU stat and virtual memory is affected. Virtual memory
mapping of the current process image is replaced by virtual
memory of new process image.
533
Systems Programming - V 3.0
We have two .c files here
exec.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("PID of exec.c = %d\n", getpid());
char *args[] = {"Helloexec", "C", "Programming", NULL};
execv("./helloexec", args);
printf("Back to exec.c");
return 0;
}
534
Systems Programming - V 3.0
helloexec.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("We are in helloexec.c\n");
printf("PID of helloexec.c = %d\n", getpid());
return 0;
} Output :
PID of exec.c = 4733
We are in helloexec.c
PID of helloexec.c = 4733
535
Systems Programming - V 3.0
536
Systems Programming - V 3.0
Process related system calls – exit
537
Systems Programming - V 3.0
Process related system calls – exit
#include <stdio.h> else if (pid == 0)
#include <unistd.h> {
#include<sys/types.h> execl("/bin/ls","ls","-l",0);
#include<sys/wait.h> printf("Exec failed\n");
int main() exit(2);
{
}
pid_t pid;
int status;
else
const char *ls_argv[] = {"ls", "-a",0}; {
const char *ls_envp[] = printf("parent process\n");
{"PATH=/bin:/usr/bin",0}; }
printf("fork program starting \n"); wait(&status); // waitpid(pid,
pid = fork(); &status,0);
if (pid < 0 ) printf("Child exited already now I am
{ exiting\n");
printf("fork failed\n");
return 0;
exit(1);
}
} 538
Systems Programming - V 3.0
Process related system calls – exit
Output:
539
Systems Programming - V 3.0
Process related system calls – signal
540
Systems Programming - V 3.0
Process related system calls – signal
541
Systems Programming - V 3.0
Process related system calls – signal
542
Systems Programming - V 3.0
Process related system calls – signal
543
Systems Programming - V 3.0
Process related system calls – signal
544
Systems Programming - V 3.0
Process related system calls – signal
545
Systems Programming - V 3.0
Process related system calls – signal
546
Systems Programming - V 3.0
Process related system calls – signal
547
Systems Programming - V 3.0
Process related system calls – kill
548
Systems Programming - V 3.0
Process related system calls – kill & raise
549
Systems Programming - V 3.0
System calls for IPC: pipe()
The pipe() system function is used to open file
descriptors, which are used to communicate
between different Linux processes. In short,
the pipe() function is used for inter-process
communication in Linux.
550
Systems Programming - V 3.0
System calls for IPC: pipe()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int pipefds[2];
if(pipe(pipefds) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
printf("Read File Descriptor Value: %d\n", pipefds[0]);
printf("Write File Descriptor Value: %d\n", pipefds[1]);
return EXIT_SUCCESS;
}
551
Systems Programming - V 3.0
System calls for IPC: pipe()
• The header file of pipe() unistd.h
• The main() function, defined the pipefds two element integer
array.
• Then, ran the pipe() function to initialize the file descriptors
array pipefds as follows. pipe(pipefds)
• also checked for errors using the return value of the pipe()
function.
• It used the exit() function to terminal the program in case the
pipe function fails.
• Then, printed the value of the read and write pipe file
descriptors pipefds[0] and pipefds[1] respectively.
552
Systems Programming - V 3.0
System calls for IPC: dup()
• dup() and dup2() create a copy of the file
descriptor oldfd.
• After a successful return from dup() or dup2(),the old
and new file descriptors may be used interchangeably.
They refer to the same open file description
(see open(2)) and thus share file offset and file status
flags; for example, if the file offset is modified by
using lseek(2) on one of the descriptors, the offset is
also changed for the other.
553
Systems Programming - V 3.0
System calls for IPC: dup()
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int old_fd, new_fd;
old_fd=open("test.txt",O_RDWR);
printf("File descriptor is %d\n",old_fd);
new_fd=dup(old_fd);
printf("New file descriptor is %d\n",new_fd);
}
554
Systems Programming - V 3.0
Contact Session – 13
Course Name :
Systems Programming
Dr. Parag
Tamhankar
Agenda
⮚ Assemblers
⮚ Assembler’s functions
⮚ Assembler directives
⮚ Object code structure
⮚ Object code
⮚ Two pass assembler
⮚ Data structures for two pass assembler
⮚ Operation code table
⮚ Symbol table and location counter
556
Systems Programming - V 3.0
Software
557
Systems Programming - V 3.0
System Software
• System software is computer software designed to
operate the computer hardware and to provide a
platform for running application software.
• Examples :
– Loaders
– Assembler
– Linkers
– Operating system
– Compilers
– Editors
558
Systems Programming - V 3.0
Assemblers
559
Systems Programming - V 3.0
Assemblers
560
Systems Programming - V 3.0
What is an Assembler & Assembly Language?
566
Systems Programming - V 3.0
Two Pass Assembler
Pass 1 (Analysis)
•This part scans the program looking for symbols, labels,
variables, etc. and organizes them in labels.
– Passes through the instructions in sequence, looking for
symbol addresses.
– Create a symbol and literal table
– Keep track of the location counter
– Process Pseudo operation(Assembler directives)
– Error checking
567
Systems Programming - V 3.0
Two Pass Assembler
Pass 2 (synthesis)
•If no errors are found in pass one then the second pass
assembles the code into object code.
– Symbolic addresses are replaced with absolute addresses
– Symbolic opcodes are replace with binary opcodes
– Perform processing of assembler directives not done in
Pass 1
– Write the object program and the assembly listing
569
Systems Programming - V 3.0
Data Structures
570
Systems Programming - V 3.0
Data Structures
571
Systems Programming - V 3.0
Data Structures
572
Systems Programming - V 3.0
Data Structures
573
Systems Programming - V 3.0
Pseudo code
574
Systems Programming - V 3.0
Pseudo code
575
Systems Programming - V 3.0
Pseudo code
576
Systems Programming - V 3.0
Copy Program Before LOC is assigned by
Assembler
Line LOC Source Startement Object Code
5 COPY START 1000
10 FIRST STL RETADR
15 CLOOP JSUB RDREC
20 LDA LENGTH
25 COMP ZERO
30 JEQ ENDFILL
35 JSUB WRREC
40 J CLOOP
45 ENDFILL LDA EOF
50 STA BUFFER
55 LDA THREE
60 STA LENGTH
65 JSUB WRREC
Systems Programming 577
Location Address and Object Code for each
instruction
• Based on the starting address all the instructions are assigned
with memory.
– In our example, starting address is 1000
– All instruction occupies 3 bytes, so second instruction LOC
will be 1003 and goes on…
– All the LOC addresses are written in hexa-decimal value
• Opcode has its mnemonic value and after that address for its
corresponding label is specified, so for each line object code is
specified.
• Converted all the instruction into its object code.
579
Systems Programming - V 3.0
Program – takes input from input device
F1 and copies them to output device 05
580
Systems Programming - V 3.0
Example: Source Program to Object Code
581
Systems Programming - V 3.0
Example: Source Program to Object Code
582
Systems Programming - V 3.0
Object Program
Simple object program format contains 3 types of records
– Header
• Starting address, program name and length
– Text
• Translated instructions and data of the program
together with an indication of the addresses where
these are to be loaded
– End
• Marks the end of the program and specifies the
address in the program where the execution is to
begin
583
Systems Programming - V 3.0
Object Program
584
Systems Programming - V 3.0
Object Code
585
Systems Programming - V 3.0
Object Code
586
Systems Programming - V 3.0
Difficulties: Forward Reference
587
Systems Programming - V 3.0
Example 2: Generate Object
Program
LABEL OPCODE Operand
• Generate the complete SUM START 4000(H)
Course Name :
Systems Programming
597
Systems Programming - V 3.0
Basic Definition
Loading - which allocates memory location and brings the
object program into memory for execution - (Loader)
598
Systems Programming - V 3.0
Role of Loader
Translator – Assembler/Compiler
Memory
599
Systems Programming - V 3.0
Role Of Loader And Linker
Memory
Source Object
Program Assembler Linker
Program Object
program
ready for
Executable execution
Code
Loader
600
Systems Programming - V 3.0
• Source Program – Assembly Language
• Object Program - From assembler
• Contains translated instructions and data values from
the source program
• Executable Code - From Linker
• Loader - Loads the executable code to the specified
memory locations and code gets executed.
601
Systems Programming - V 3.0
Need For Linking And Loading
602
Systems Programming - V 3.0
We Need…three Processes
•Loading - which allocates memory location and brings the object
program into memory for execution
•Relocation - which modifies the object program so that it can be
loaded at an address different from the location originally
specified.
•Linking- which combines two or more separate object programs
and supplies the information needed to allow references between
them
•A loader is a system program that performs the loading
function. Many loaders also support relocation and
linking. Some systems have a linker to perform the linking
and a separate loader to handle relocation and loading.
603
Systems Programming - V 3.0
Basic Loader Functions
604
Systems Programming - V 3.0
Type Of Loaders
• Absolute loader
• Bootstrap loader
• Relocating loader (relative loader)
• Direct linking loader
605
Systems Programming - V 3.0
Absolute Loader
• Operation is very simple
• The object code is loaded to specified locations
in the memory
• At the end the loader jumps to the specified
address to begin execution of the loaded
program
606
Systems Programming - V 3.0
Role Of Absolute Loader
1000
Object Absolute Object
Program Loader program
ready for
execution
2000
Memory
607
Systems Programming - V 3.0
Absolute Loader
For a simple absolute loader, all functions are
accomplished in a single pass as follows:
609
Systems Programming - V 3.0
Absolute Loader Implementation
610
Systems Programming - V 3.0
Begin
read Header record
verify program name and length
read first Text record
while record type is <> ‘E’ do
begin
{if object code is in character form, convert into
internal representation}
move object code to specified location in memory
read next object program record
end
jump to address specified in End record
end
611
Systems Programming - V 3.0
Object Program
• An object program is loaded at the address specified
on the START directive.
• No relocation or linking is needed
• Thus is very simple
612
Systems Programming - V 3.0
Absolute Loader
614
Systems Programming - V 3.0
A Simple Bootstrap Loader
615
Systems Programming - V 3.0
Example (Sic Bootstrap Loader)
616
Systems Programming - V 3.0
Bootstrap Loaders
619
Systems Programming - V 3.0
SIC uses the above mentioned second method.
620
Systems Programming - V 3.0
SIC uses the above mentioned second method.
621
Systems Programming - V 3.0
Relocating Loader
622
Systems Programming - V 3.0
Program Written in SIC/XE
623
Systems Programming - V 3.0
Base-relative
1. Program Relocation
2. Program Linking
626
Systems Programming - V 3.0
Program Relocation (Relocating Loader)
627
Systems Programming - V 3.0
Program Relocation (Relocating Loader)
628
Systems Programming - V 3.0
Relocation
629
Systems Programming - V 3.0
Relocating Loaders
1. Modification Record
2. Relocation Bit
630
Systems Programming - V 3.0
Modification Record
631
Systems Programming - V 3.0
The Modification has the following format:
633
Systems Programming - V 3.0
Relocation Bit
635
Systems Programming - V 3.0
Relocation Bit
636
Systems Programming - V 3.0
Relocation Bit
638
Systems Programming - V 3.0
Direct Linking Loaders
Course Name :
Systems Programming
System calls
System calls for Process management
System calls for memory management
641
Systems Programming - V 3.0
CS-14 Overview
• What is system call? Types of system calls.
• File Related System calls
• Open, Create, Close, Read, write, lseek, mkdir, rmdir, rename,
link, simlink, unlink covered.
• Process Related System calls
• Fork, wait, exec covered
• We will continue with other process related system calls such
as: exit, signal, kill, raise
642
Systems Programming - V 3.0
Process related system calls – exit
643
Systems Programming - V 3.0
Ex-1: exit
#include <stdio.h> else if (pid == 0)
#include <unistd.h> {
#include<sys/types.h> execl("/bin/ls","ls","-l",0);
#include<sys/wait.h> printf("Exec failed\n");
int main() exit(2);
{
}
pid_t pid;
int status;
else
const char *ls_argv[] = {"ls", "-a",0}; {
const char *ls_envp[] = printf("parent process\n");
{"PATH=/bin:/usr/bin",0}; }
printf("fork program starting \n"); wait(&status); // waitpid(pid,
pid = fork(); &status,0);
if (pid < 0 ) printf("Child exited already now I am
{ exiting\n");
printf("fork failed\n");
return 0;
exit(1);
}
} 644
Systems Programming - V 3.0
Ex-1: exit
Output:
645
Systems Programming - V 3.0
Ex-1: exit
• The program demonstrates the use of the fork() and execl() system calls to create
a child process and execute the ls command with specific arguments and
environment variables. It also illustrates the use of wait() or waitpid() to
synchronize the parent process with the child process.
• pid = fork();: Creates a child process. If pid < 0: Forking failed, print an error
message and exit. If pid == 0: In the child process, execute the ls command using
execl(). If pid > 0: In the parent process, proceed to the next step.
648
Systems Programming - V 3.0
Process related system calls – signal
649
Systems Programming - V 3.0
Process related system calls – signal
650
Systems Programming - V 3.0
Process related system calls – signal
651
Systems Programming - V 3.0
Process related system calls – signal
652
Systems Programming - V 3.0
Process related system calls – signal
653
Systems Programming - V 3.0
Process related system calls – signal
654
Systems Programming - V 3.0
Ex-2: signal
Given C code
demonstrates how to
handle the SIGINT signal
(typically generated by
pressing Ctrl+C) and
write a message to a file
before exiting.
o/p
655
Systems Programming - V 3.0
Ex-2: signal
• (void)signal(SIGINT, leave): Registers the leave function to handle the SIGINT
signal.
• temp_file = fopen("tmp", "w"): Opens the file "tmp" in write mode.
• for(;;): This is an infinite loop that will continue until the SIGINT signal is
received or the program is terminated manually.
• printf("Ready...\n"): Prints a message indicating that the program is ready.
• (void)getchar(): Waits for the user to press any key.
• exit(EXIT_SUCCESS): Exits the program with a success status. This statement is
unreachable because the infinite loop will continue until the SIGINT signal is
received.
• fprintf(temp_file, "\nInterrupted...\n"): Writes the message "Interrupted...\n"
to the temporary file.
• fclose(temp_file): Closes the temporary file.
• exit(sig): Exits the program with the signal number as the exit status. This
indicates that the program was terminated due to the SIGINT signal.
657
Systems Programming - V 3.0
Process related system calls – kill & raise
658
Systems Programming - V 3.0
Ex-3: kill
• The program demonstrates
the use of the fork system
call to create a child process.
• The child process performs a
simple task (sleeping for 10
seconds) and then exits.
• The parent process sends an
interrupt signal to the child
process using kill.
• The parent process waits for
the child to terminate using
wait and prints its exit status.
661
Systems Programming - V 3.0
System calls for IPC: pipe()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int pipefds[2];
if(pipe(pipefds) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
printf("Read File Descriptor Value: %d\n", pipefds[0]);
printf("Write File Descriptor Value: %d\n", pipefds[1]);
return EXIT_SUCCESS;
}
662
Systems Programming - V 3.0
System calls for IPC: pipe()
• The header file of pipe() unistd.h
• The program creates a pipe using the pipe function.
• A pipe is a special type of file that allows communication
between processes. It consists of two file descriptors: one for
reading and one for writing.
• The pipe function returns an array of two integers, pipefds[0] and
pipefds[1], which represent the read and write file descriptors,
respectively.
• The program then prints the values of these file descriptors to
the console.
663
Systems Programming - V 3.0
System calls for IPC: dup()
• dup() and dup2() create a copy of the file
descriptor oldfd.
• After a successful return from dup() or dup2(),the old
and new file descriptors may be used interchangeably.
They refer to the same open file description
(see open(2)) and thus share file offset and file status
flags; for example, if the file offset is modified by
using lseek(2) on one of the descriptors, the offset is
also changed for the other.
664
Systems Programming - V 3.0
System calls for IPC: dup()
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int old_fd, new_fd;
old_fd=open("test.txt",O_RDWR);
printf("File descriptor is %d\n",old_fd);
new_fd=dup(old_fd);
printf("New file descriptor is %d\n",new_fd);
}
665
Systems Programming - V 3.0
System calls for IPC: dup()
• The program demonstrates the use of the open and dup
functions to open a file and create a duplicate file descriptor.
• The open function creates a new file descriptor and returns
its value.
• The dup function creates a duplicate file descriptor for an
existing open file.
• The duplicate file descriptor shares the same file descriptor
table entry as the original file descriptor, which means they
refer to the same open file.
• *brk(void addr):
• Used to adjust the program's data segment (heap) size.
• addr: A pointer to the desired new address for the break. If
NULL, the current break address is returned.
• On success, the new break address is returned. On failure, -1 is
returned and errno is set to indicate the error.
• sbrk(intptr_t increment):
• Similar to brk, but adjusts the break by a specified increment.
• increment: The amount by which to adjust the break (positive
for increasing, negative for decreasing).
• On success, the new break address is returned. On failure, -1 is
returned and errno is set to indicate the error.
o/p
• Release memory using brk: The brk function is used to set the program's break
address back to its original value, effectively releasing the previously allocated
memory.
• This program illustrates how brk and sbrk can be used to dynamically adjust
the program's memory usage. However, it's important to note that brk and
sbrk are generally not recommended for modern applications due to their
limitations and potential fragmentation issues. mmap is often preferred for
more flexible and efficient memory management.
• void *mmap(void *addr, size_t length, int prot, int flags, int fildes,
off_t off):
• The mmap system call in Linux provides a powerful and flexible
way to map files or devices into the address space of a process.
• This allows for efficient memory-mapped I/O operations and
shared memory communication between processes.
• Parameters are discussed below.
Parameters
• addr: starting address of the mapped region. If NULL, the kernel chooses an address.
• length: The size of the mapped region in bytes.
• prot: Protection flags for the mapped region:
• PROT_READ: Read-only access.
• PROT_WRITE: Read-write access.
• PROT_EXEC: Execute access.
• flags: Flags to control the mapping:
• MAP_PRIVATE: Creates a private copy of the mapped region.
• MAP_SHARED: Creates a shared mapping, where changes made by one process
are visible to other processes.
• MAP_ANONYMOUS: Creates an anonymous mapping (not associated with a file).
• MAP_FIXED: Attempts to fix the mapping at the specified address.
• fildes: The file descriptor of the file or device to map.
• off: The offset within the file or device from which to start mapping.
o/p