System Programming
System Programming
CO4 To provide understanding of assemblers, linkers and • Since then, it has spread world-wide, with tens of thousands of systems installed,
from Micro-Computers to Main-Frames.
loaders
7
3
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Agenda
10
Main-Memory Management
Operating System is Responsible
• Memory is a large array of words or bytes, each with its own
• Resource allocator – manages and allocates address. It is a repository of quickly accessible data shared
resources. by the CPU and I/O devices.
• Main memory is a volatile storage device. It loses its
• Control program – controls the execution of user contents in the case of system failure.
programs and operations of I/O devices .
• The operating system is responsible for the following
• Kernel – the one program running at all times (all activities in connections with memory management:
else being application programs). – Keep track of which parts of memory are currently being used and by
whom.
– Decide which processes to load when memory space becomes
available.
– Allocate and deallocate memory space as needed.
12 16
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
File Management Unix Architecture
•The main concept that unites all the versions of Unix is the following four basics
• A file is a collection of related information defined by its •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
creator. Commonly, files represent programs (both source file management.
and object forms) and data.
• The operating system is responsible for the following •Shell − The shell is the utility that processes your requests.
activities in connections with file management: When you type in a command at your terminal, the shell interprets the
command and calls the program that you want.
– File creation and deletion.
Ex: C Shell, Bourne Shell and Korn Shell are the most famous shells which are
– Directory creation and deletion. available with most of the Unix variants.
– Support of primitives for manipulating files and directories.
– Mapping files onto secondary storage. •Commands and Utilities − There are various commands and utilities which you
can make use of in your day to day activities.
Ex: 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.
17
•All files are then organized into directories. These directories are further
BITS Pilani, Pilani Campus organized into a tree-like structure called the filesystem. BITS Pilani, Pilani Campus
Unix Architecture
Secondary-Storage Management
18
Unix Architecture
I/O Subsystem Management
•The block diagram of the UNIX OS
kernel shows various modules and their
relationships with each other
• Keeping track of status of the I/O devices •The system call and library interface
made the border between user
• Deciding who gets the device, for how long and programs and the kernel.
when •System calls look like ordinary function
calls in C programs.
• Allocating a device to a process and de-allocation •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
19 provide a more sophisticated use of the
BITS Pilani, Pilani Campus
system calls. BITS Pilani, Pilani Campus
A UNIX command is an action request given to the UNIX shell for execution.
• Simple and yet powerful
All UNIX commands apply an action or a series of actions to some input data and
• A multiuser, multitasking, portable operating create some output data.
All UNIX commands are case sensitive.
system
The command format is
• Interaction with the system via a command $ verb [options] [arguments]
interpreter – shell where
verb is the command name
options modify how the action is applied and
On the lighter side, arguments provide additional information to the command
UNIX is simple. But, you need to be a genius to understand
its simplicity! There are a few commands (like pwd) that don’t take any arguments,
some commands (like who, ls) that may or may not take any arguments and
some commands (like cut) that compulsorily take arguments.
20 24
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Internal and External Commands When things go wrong
Terminal settings directly impact keyboard operation, and you should know
The commands that are built-in as part of the shell are called internal commands. which keys to press when things don’t quite work as expected.
Example: echo command
Keystroke or Function
A program or file having an independent existence in the /bin directory (or /usr/bin), command
is called as an external command. [Ctrl-h] Erases text
Example: ls, wc, cal, bc, more … [Ctrl-c] or Delete Interrupts a command
[Ctrl-d] Terminates login session or a program that expects its input from
PATH variable: Contains the sequence of directories that the shell searches to look for keyboard
a command. [Ctrl-s] Stops scrolling of screen output and locks keyboard
$ echo $PATH [Ctrl-q] Resumes scrolling of screen output and unlocks keyboard
/bin:/usr/bin:/usr/local/bin:/usr/local/java/bin:. [Ctrl-u] Kills command line without executing it
[Ctrl-\] Kills running program but creates a core file containing the memory
When you issue a command, image of the program
The shell sees if it is a built-in command. If so, it executes it directly. [Ctrl-z] Suspends process and returns shell prompt; use fg to resume job
If not a built-in, it searches the associated file in the directories specified in PATH. If [Ctrl-j] Alternative to [Enter]
found, it executes the file. [[Ctrl-m] Alternative to [Enter]
Otherwise, it triggers a error message. stty sane Restores terminal to normal status
25 29
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
33 37
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Directory file
• Folder that contains other files and • Echo - displays message on screen of
subdirectories issue prompt for input.
• Provides a means to organize files in Usage
hierarchical structure $echo GNU/Linux
• To create : mkdir command $echo $SHELL $PATH
• To remove : rmdir command $echo “Enter input value: \c”
Enter input value:$
34 38
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Basic Commands
• banner- prints a banner
• In Linux bash shell interprets escape sequences
– Usage - $ banner Wipro
only with the –e option.
• cal- calendar of the month. • Bash has –n option as substitute for \c
– Syntax – cal [ [ month] year ] • Korn shell doesn’t use –n.
• Takes 2 arguments
• Echo’s behaviour varies across shells so POSIX
• Month (2 args) and year (1 arg)
recommends printf as a replacement of echo.
– Usage - $cal 9 2009
– $cal 2010
36 40
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
passwd – changing your password
• Passwd – note the spelling
$who –H
• user can change password only for his/her
account. -H gives the header option
• Superuser can change the password of every $who –Hu
NAME LINE TIME IDLE PID COMMENTS
user using the same command.
root console Sep 19 12:50 0:48 11041 (:0)
• The command expects you to respond three Krishna pts/5 Sep 19 12:50 0:33 11090 (sys1.lab1.com)
times. Rama pts/2 Sep 19 13:01 . 13456 (sys5.lab2.com)
– Prompts for old password
$who am i
– validates the current password
– If correct prompts for new password
– Prompts for re-entering new password 41 45
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• Don’t choose a password similar to the old one. $uname -n -- displays system name
• Don’t use commonly used names like name of friend, Lab1sys2 -- which is a part of the
pets etc. A system may check with its own dictionary domain -- name
and throw out those password that are easily guessed. $hostname -- an alternate command
• Use a mixture of alphabetic and non alphabetic chars. Lab1sys2
• Enterprise UNIX won’t allow passwords that are fully • Hostname is very much essential to identify your
numeric or fully alphabetic. computer on the network.
• Don’t write the password in an easily accessible
• Hostname is a part of your machine's domain
document.
name(sys1.lab2.com).
43 47
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
$bc
12*12 ; 2^32 multiple calculations
144
4294967296
12/5
2 Decimal portion truncated
The Mail command in unix or linux system is used to send emails to the
users, to read the received emails, to delete the emails etc.
• The syntax of mail command is:
• mail [options] to-address [-- sendmail-options]
• 1. Sending sample email to user
The basic functionality of the mail command in unix or linux system is to System Pro
send an email to the user.
3. Send mail to more than one user You can send email to more than one user
by specifying the users in comma separated list.
• It schedules them to run in turn until they voluntarily relinquish the CPU w
or until the kernel preempts them when their recent run time exceeds a tim
• The scheduler then chooses the highest priority eligible process to run; the
again when it is the highest priority eligible process available
Unix Architecture
The UNIX Operating System
• 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.
• fileSimple
• It interacts with the hardware and most of the tasks like memory management, task scheduling and management.
and yet powerful
• Shell − The shell is the utility that processes your requests.
• A multiuser, multitasking, portable operating system
• • Interaction
When you type in a command at your terminal, the shell interprets the command and calls the program that you want. with the system via a command interpret
• C Shell, Bourne Shell and Korn Shell are the most famous shells which are available with most of the Unix variants.
• Commands and Utilities − There are various commands and utilities which you can make use of in your day to day
activities. On the lighter side,
• cp, mv, cat and grep, etc. are few examples of commands and utilities. UNIX is simple. But, you need to be a genius to understa
its simplicity!
• 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.
• 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.
Unix Architecture man pages
•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
UNIX offers an online help facility in the man command.
tasks like memory management, task scheduling and file management. man displays the documentation of the specified command.
•Shell − The shell is the utility that processes your requests. Example:
$ man wc displays help on wc command
When you type in a command at your terminal, the shell interprets the command and calls the
program that you want.
man uses a pager program, which displays this documentati
Ex: C Shell, Bourne Shell and Korn Shell are the most famous shells which are available with most of the at a time
page
Unix variants.
man is configured to be used with a specific pager.
•Commands and Utilities − There are various commands and utilities which you can make use of in your
Two available pagers are:
day to day activities. more, a Berkeley pager, as an alternative to the AT&T pg comma
Ex: cp, mv, cat and grep, etc. are few examples of commands and utilities. less, the standard pager on Linux systems, also available on UN
•Files and Directories − All the data of Unix is organized into files. modeled after vi editor and is more powerful than more..
•All files are then organized into directories. These directories are further organized into a tree-like
structure called the filesystem.
BITS Pilani, Pilani Campus
Unix Architecture
A sample man Page
•The block diagram of the UNIX OS kernel shows various
modules and their relationships with each other User Commands wc(1)
•The system call and library interface made the border NAME
wc – displays a count of lines, words and characters in a file
between user programs and the kernel. SYNOPSIS
wc [-c | -m | -C] [-lw] [file ...]
•System calls look like ordinary function calls in C DESCRIPTION
The wc utility reads one or more input files and, by default, writes the
programs. newline characters, words and bytes contained in each input file
•Libraries map these function calls to the primitives standard output. The utility also writes a total count for all named
more than one input file is specified.
needed to enter the operating system. OPTIONS
The following options are supported:
•Assembly language programs may invoke system calls -c Count bytes.
directly without a system call library. -m Count characters.
-C same as –m.
•Programs frequently use other libraries such as the -l Count lines.
-w Count words delimited by white spaces or new line characters ...
standard I/O library to provide a more sophisticated use of OPERANDS
the system calls. The following operand is supported:
file A path name of an input file. If no file operands are specified,
the standard input will be used.
EXIT STATUS
See largefile(5) for the description of the behavior of wc when encounter
greater than or equal to 2 Gbyte (2 **31 bytes)
SEE ALSO
cksum(1), isspace(3C), iswalpha(3C), iswspace(3C), largefile(5), ...
BITS Pilani, Pilani Campus
The commands that are built-in as part of the shell are called internal commands. • Unix Commands
Example: echo command
• When you first log into a unix system, you are prese
A program or file having an independent existence in the /bin directory (or /usr/bin), is called
something that looks like the following:
as an external command.
Example: ls, wc, cal, bc, more …
/home/jaya#
PATH variable: Contains the sequence of directories that the shell searches to look for a
command.
• That “something” is called a prompt. As its name would sug
$ echo $PATH
/bin:/usr/bin:/usr/local/bin:/usr/local/java/bin:.
prompting you to enter a command.
When you issue a command,
The shell sees if it is a built-in command. If so, it executes it directly. • Every unix command is a sequence of letters, numb
If not a built-in, it searches the associated file in the directories specified in PATH. If found, it
executes the file. characters. But there are no spaces.
Otherwise, it triggers a error message.
14 18
BITS Pilani
Unix Commands
Unix - Basics
• Who Are You?
• While you're logged into the system, you might be willing to know : Who am I?
There are two major types of shells in unix: • $ whoami
Bourne shells • krishna
C shells.
• Who is Logged in?
Steven Bourne wrote the original unix shell sh,and most shells
• Sometime since
you might be interested to know who is logged in to the computer at the sa
then end in the letters sh to indicate they are extentions on are
• There thethree
original
commands available to get you this information, based on how much
idea. other users:
• users, who, and w.
• $ users
Linux comes with a Bourne shell called bash written by the Free
• krishna bablu qadir
Software Foundation.
• $ who
Bash stands for Bourne Again Shell and is the default• krishna
shellttyp0toOctuse
8 14:10 (limbo)
running linux • bablu ttyp2 Oct 4 09:08 (calliope)
• qadir ttyp4 Oct 8 12:09 (dent)
20
BITS Pilani
To search for a man page, enter man followed by the name of the command to find .
• Ordinary Files − An ordinary file is a file on the system that contains data, te
instructions. In this tutorial, you look at working with ordinary files.
For example:
• Special Files − Some special files provide access to hardware such as hard d
21 modems, and Ethernet adapters.
BITS Pilani
• login : krishna
• krishna's password:
• Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
• $
UNIX files and directories UNIX files and directories
• Listing Files • Creating Files:
• To list the files and directories stored in the current directory, use the following
• Youcommand − vi editor to create ordinary files on any Unix system.
can use the
• $ ls • $ vi filename
• bin hosts lib res.03
• The above command will open a file with the given filename.
• ch07 hw1 pub test_results
• ch07.bak hw2 res.01 users • Now, press the key i to come into the edit mode.
• docs hw3 res.02 work • Once you are in the edit mode, you can start writing your content in the file as in t
• This is about
• The command ls supports the -l option which would help you to get more information unix file....I
thecreated it for the first time.....
listed files − • I'm going to save this content in this file.
• $ ls -l • Once you are done with the program, follow these steps −
• drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml • Press the key esc to come out of the edit mode.
• -rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg • Press two keys Shift + ZZ together / wq to come out of the file completely.
• drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
• drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia • Display Contents of a File
• -rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
• $ cat filename
• We use * to match 0 or more characters, a question mark (?) matches with a single character.
• Renaming Files
• $ ls ch*.doc • To change the name of a file, use the mv command. Following is the basic syntax −
• Displays all the files, the names of which start with ch and end with .doc − • $ mv old_file new_file
• The mv command will move the existing file completely into the new file.
• ch01-1.doc ch010.doc ch02.doc ch03-2.doc
• ch04-1.doc ch040.doc ch05.doc ch06-2.doc • Deleting Files
• ch01-2.doc ch02-1.doc c • To delete an existing file, use the rm command. Following is the basic syntax −
• $ rm filename
• Here, * works as meta character which matches with any character. • Caution − A file may contain useful information. It is always recommended to be careful while u
• If you want to display all the files ending with just .doc, then you can use the• following
It is better tocommand − along with rm command. It will ask for a confirmation before dele
use the -i option
• You can remove multiple files at a time with the command given below −
• $ls *.doc
• $ rm filename1 filename2 filename3
BITS Pilani
BITS Pilani
• 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 comm
if it successfully creates the requested directory.
• If you give more than one directory on the command line, mkdir creates each of th
example, −
• $mkdir docs pub
37
• Creates the directories docs and pub under the current directory.
BITS Pilani
• stdout − This is referred to as the standard output and the associated file descriptor is 1.
• Changing Directories
• This is also represented as STDOUT. • You can use the cd command to do more than just change to a home directory. You can use it to chan
a valid absolute or relative path. The syntax is as given below −
• The Unix program will write the default output at STDOUT • $cd dirname
• Here, dirname is the name of the directory that you want to change to. For example, the command −
• stderr − This is referred to as the standard error and the associated file • $cd /usr/local/bin
descriptor is 2.
• Changes to the directory /usr/local/bin.
• This is also represented as STDERR. • From this directory, you can cd to the directory /usr/home/amrood using the following relative path −
• The Unix program will write all the error messages at STDERR. • $cd ../../home/amrood
Unix / Linux - Directory Management Unix / Linux - File Permission / Access Mod
• Renaming Directories • Changing Permissions
• The mv (move) command can also be used to rename a directory. The syntax is as follows • $chmod − o+wx testfile
• $mv olddir newdir • $ls -l testfile
• You can rename a directory mydir to yourdir as follows − • -rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
• $mv mydir yourdir • $chmod u-x testfile
• The directories . (dot) and .. (dot dot) • $ls -l testfile
• -rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
• 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 • $chmod g = rx testfile
directory.
• If we enter the command to show a listing of the current working directories/files and • $lsuse
-l testfile
the -a option to
list all the files and the -l option to provide the long listing, we will receive the following• result.
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
• $ls -la
• drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 . • Here's how you can combine these commands on a single line −
• drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
• ---------- 1 teacher class 4210 May 1 08:27 .profile • $chmod o+wx,u-x,g = rx testfile
• -rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo • $ls -l testfile
• -rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Mod
• File ownership is an important component of Unix that provides a secure method for storing files. • Using chmod with Absolute Permissions
• 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.
• The second way to modify permissions with the chmod command is to use
each set of permissions for 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. • Each permission is assigned a value, as the following table shows, and the t
• Other (world) permissions − The permissions for others indicate what action all other users can perform on the file. permissions provides a number for that set.
• The Permission Indicators
• While using ls -l command, it displays various information related to file permission as follows −
• $ls -l /home/amrood
• Number Octal Permission Representation Ref
• -rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile • 0 No permission ---
• drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
• 1 Execute permission --x
• Here, the first column represents different access modes, i.e., the permission associated with a file or a directory. • 2 Write permission -w-
•
• 3
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) − Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
• The first three characters (2-4) represent the permissions for the file's owner. • 4 Read permission r--
• 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.
• 5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
• For example, -rwxr-xr-- represents that the group has read (r) and execute (x) permission, but no write permission. • 6 Read and write permission: 4 (read) + 2 (write) = 6 rw-
• The last group of three characters (8-10) represents the permissions for everyone else. • 7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx
• For example, -rwxr-xr-- represents that there is read (r) only permission
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Mod
• File Access Modes • Using chmod with Absolute Permissions
• Here's an example using the testfile.
• The permissions of a file are the first line of defense in the security of a Unix• system. The basic
Running ls -l on the testfile shows that the file's permissions are as follows −
building blocks of Unix permissions are the read, write, and execute permissions, which have been
described below − • $ls -l testfile
• -rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
• 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. • Then each example chmod command from the preceding table is run on the testfile, followed by ls –l, so you can se
• Execute - User with execute permissions can run a file as a program. • $ chmod 755 testfile
• $ls -l testfile
• -rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
• Directory Access Modes
• Directory access modes are listed and organized in the same manner as any• other $chmodfile. There are a
743 testfile
few differences that need to be mentioned − • $ls -l testfile
• Read - Access to a directory means that the user can read the contents. The• user-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
can look at the
filenames inside the directory.
• $chmod 043 testfile
• Write - Access means that the user can add or delete files from the directory.• $ls -l testfile
• Execute - Executing a directory doesn't really make sense, so think of this as• a----r---wx
traverse permission.
1 amrood users 1024 Nov 2 00:10 testfile
• A user must have execute access to the bin directory in order to execute the ls or the cd command.
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Mod
• Changing Permissions • Changing Owners and Groups
• To change the file or the directory permissions, you use the chmod (change mode) command. • While creating an account on Unix, it assigns a owner ID and a group ID to each user. All th
• There are two ways to use chmod — the symbolic mode and the absolute mode. above are also assigned based on the Owner and the Groups.
• Two commands are available to change the owner and the group of files −
• Using chmod in Symbolic Mode • chown − The chown command stands for "change owner" and is used to change the owner
• The easiest way for a beginner to modify file or directory permissions is to use the symbolic•mode.
chgrp − The chgrp command stands for "change group" and is used to change the group of
• With symbolic permissions you can add, delete, or specify the permission set you want by using the operators in the
following table. • Changing Ownership
• The chown command changes the ownership of a file. The basic syntax is as follows −
• Chmod operator & Description • $ chown user filelist
• + Adds the designated permission(s) to a file or directory. • The value of the user can be either the name of a user on the system or the user id (uid) of
• - Removes the designated permission(s) from a file or directory. • The following example will help you understand the concept −
• = Sets the designated permission(s). • $ chown amrood testfile
• Changes the owner of the given file to the user amrood.
• Here's an example using testfile. Running ls -1 on the testfile shows that the file's permissions are as−follows
• NOTE − user, root, has the unrestricted capability to change the ownership of an
The super
• $ls -l testfile change the ownership of only those files that they own.
• -rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Mod
• Changing Group Ownership • Setting the Terminal Type
• The chgrp command changes the group ownership of a file. • Usually, the type of terminal you are using is automatically configured by either the login or gett
• Sometimes, the auto configuration process guesses your terminal incorrectly.
• The basic syntax is as follows − • If your terminal is set incorrectly, the output of the commands might look strange, or you might
the shell properly.
• To make sure that this is not the case, most users set their terminal to the lowest common deno
• $ chgrp group filelist • $TERM=vt100
• The value of group can be the name of a group on the system or the group ID (GID) of a group
on the system. • Setting the PATH
• When you type any command on the command prompt, the shell has to locate the command b
•
• Following example helps you understand the concept − The PATH variable specifies the locations in which the shell should look for commands.
• Usually the Path variable is set as follows −
• $PATH=/bin:/usr/bin
• $ chgrp special testfile • Here, each of the individual entries separated by the colon character (:) are directories.
•
• Changes the group of the given file to special group. If you request the shell to execute a command and it cannot find it in any of the directories give
message similar to the following appears −
• $hello
• hello: not found
• For example, first we set a variable TEST and then we access its value using the echo command −
spell
• $TEST="Unix Programming"
• $echo $TEST spell is very simple unix spelling program, usually for American Eng
• It produces the following result. spell is a filter, like most of the other programs we’ve talked about.
• Unix Programming
$ spell [file1 file2 ... fileN]
• 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. 56
59 63
BITS Pilani
ed command pr command
• ed is a line-oriented text editor. • An option that's a number will print a file in that number of columns.
• For instance, the -3 option prints a file in three columns.
• The file is read, line by line, until the first column is full (by default, that takes 5
• It is used to create, display, modify and otherwise manipulate text files.
• Next, the second column is filled.
• Then, the third column is filled.
• red is a restricted ed: it can only edit files in the current directory• and cannot
If there's execute
more of the file, the first column of page 2 is filled -- and the cycle rep
shell commands.
• % pr -3 file1
• If invoked with a file argument, then a copy of file is read into the editor’s
• Oct 1buffer.
19:44 2017 file1 Page 1
• Changes are made to this copy and not directly to file itself. • Line 1 here Line 57 here Line 115 here
• Line 2 here Line 58 here Line 116 here
• Line 3 here Line 59 here Line 117 here
• Upon quitting ed, any changes not explicitly saved with a ‘w’ command
• ...are lost. ... ...
60
BITS Pilani
ed command
pr command
Editing is done in two distinct modes: command and input. +n starts displaying with the nth page of each file. The default for n i
When first invoked, ed is in command mode. -n displays n columns of output. This is the obsolete equivalent of -c
In this mode commands are read from the standard input and executed -atoorders
manipulate the across the page on output, instead of down. Yo
input lines
contents of the editor buffer. option with -n.
A typical command might look like:
,s/old/new/g -c n displays n columns of output. When you specify this option,
you had also specified the
which replaces all occurrences of the string old with new. -e and -i options. When you specify both this option and
When an input command, such as ‘a’ (append), ‘i’ (insert) or ‘c’ (change), is given, ed enters
input mode. -t, pr uses the minimum number of lines possible to display the o
This is the primary means of adding text to a file. specify this option with -m.
In this mode, no commands are available; instead, the standard input is written directly to the
editor buffer. -d produces double-spaced output.
61
BITS Pilani
pr command
pr command
• Lines consist of text up to and including a newline character. -e[char][gap] expands each occurrence of the input tab characte
• Input mode is terminated by entering a single period (.) on a line. such that the following character has the next column position
multiple of gap, plus 1.
• pr command:
-F uses form feeds to separate pages.
• The pr command is famous for printing a file neatly on a page -- with
pr normally separates
margins at top pages by sending a series of newline
and bottom, filename, date, and page numbers. length of a page.
-f for
• It can also print text in columns: one file per column or many columns uses form
each feeds to separate pages.
file.
When output is to a terminal, pr sounds the bell and waits for y
returnofbefore
• The -t option takes away the heading and margins at the top and bottom displaying the text.
each page.
pr normally separates pages by sending a series of newline
That's useful when "pasting" data into columns with no interruptions.
length of a page.
62
BITS Pilani
which cal
• Displays a path name of a command. • Calendar • % cal current m
• Searches a path environmental variable for the command and • for month • % cal 2 2000 Feb 2000
displays the absolute path. • entire year • % cal 2 2100 not a lea
• % cal 2 2400
• To find which tcsh and bash are actually in use, type: • Years range: 1 - 9999
leap yea
chsh clear
• Change Login Shell
• Login shell is the shell that interprets commands after you logged in • Clears the screen
by default. • There’s an alias for it: Ctrl+L
• You can change it with chsh (provided that your system admin • Example sequence:
allowed you to do so).
• % cal
• To list all possible shells, depending on implementation: • % clear
% chsh -l
% cat /etc/shells • % cal
• Ctrl+L
• % chsh with no arguments will prompt you for the shell.
whereis sleep
• Display all locations of a command (or some other binary, man page, or a
source file). • “Sleeping” is doing nothing for some time.
• Searchers all directories to find commands that match whereis’• Usually used for delays in shell scripts.
argument • % sleep 2 2 seconds pause
• % whereis tcsh
unalias shutdown
• Removes alias • Causes system to shutdown or reboot cleanly.
• Requires an argument. • May require superuser privileges
• % unalias cl • % shutdown -h now - stop
• % shutdown -r now - reboot
history
• Display a history of recently used • % !n
commands • repeat command n in the history
• % history • % !-1 Files
• all commands in the history • repeat last command = !!
• % history 10 • % !-2
• last 10 • repeat second last command
• % history -r 10 • % !ca
• reverse order • repeat last command that begins with
‘ca’
• % !!
• repeat last command
apropos ls
less rm
• less ("less is more") a bit more smart than the more command
• Removes file(s) and/or directories.
• to display contents of a file:
• % less filename • % rm file1 [file2] ...
• To display line numbers: • % rm -r dir1 [dir2] ...
• % less -N filename
• To display a prompt: • % rm -r file1 dir1 dir2 file4 ...
• % less -P"Press 'q' to quit" filename
• Combine the two:
• % less -NP"Blah-blah-blah" filename
• For more information:
• % man less
touch script
• By touching a file you either create it if it did not exists (with 0• Writes a log (a typescript) of whatever happened in the
length). file.
• Or you update it’s last modification and access times. • % script [file]
• There are options to override the default behavior. • % script
• % touch file • all log is saved into a file named typescript
• % man touch • % script file
• all log is saved into a file named file
• To exit logging, type:
• % exit
cp find
• Looks up a file in a directory tree.
• Copies files / directories.
• % find . -name name
• % cp [options] <source> <destination>
• % find . \(-name ‘w*’ -or -name ‘W*’ \)
• % cp file1 file2
• % cp file1 [file2] … /directory
• Useful option: -i to prevent overwriting existing files
and prompt the user to confirm.
mkdir ln
• Creates a directory. • Symbolic link or a “shortcut” in M$ terminology.
• % mkdir newdir • % ln –s <real-name> <fake-name>
• Often people make an alias of md for it.
cd chmod
• Changes your current directory to a new one. • Changes file permissions
• % cd /some/other/dir • Possible invocations
• Absolute path • % chmod 600 filename
• % cd subdir • -rw------- 1 user group 2785 Feb 8 14:18 filename
(a bit not intuitive where 600 comes from)
• Assuming subdir is in the current directory.
• % chmod u+rw filename
• % cd (the same thing, more readable)
• Returns you to your home directory. • For the assignment:
• % chmod u+x myshellscript
(mysshellscript is now executable)
• -rwx------ 1 user group 2785 Feb 8 14:18 myshellscript
pwd grep
• Displays personal working directory, i.e. your current directory.• Searches its input for a pattern.
• % pwd • The pattern can be a simple substring or a complex regular expre
• If a line matches, it’s directed to STDOUT; otherwise, it’s discarde
• % echo “blah-foo” | grep blah
• Will print the matching line
• % echo “blah-foo” | grep zee
• Will not.
• See a separate grep tutorial.
rmdir Pipes
• Removes a directory. • What's a pipe?
• % rmdir dirname • is a method of interprocess communication (IPC)
• in shells a '|' symbol used
• Equivalent: • it means that the output of one program (on one side of a pip
• % rm -r dirname input for the program on another end.
• a set of "piped" commands is often called a pipeline
• Why it's useful?
• Because by combining simple OS utilities one can easily solve
tasks
IMP Note to Students
It is important to know that just login to the session does not
guarantee the attendance.
Once you join the session, continue till the end to consider you
as present in the class.
IMPORTANTLY, you need to make the class more interactive by
responding to Professors queries in the session.
Whenever Professor calls your number / name ,you need to
respond, otherwise it will be considered as ABSENT
3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Agenda
4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Overhead
• Inodes
sector track
view • Structure of a regular file
cylinder • Directories
• Conversion of a path name to an inode
• Super block
• Inode assignment to a new file
Disk blocks are composed of The same track on each platter
one or more contiguous in a disk makes a cylinder; • Allocation of disk blocks
partitions are groups of
sectors
contiguous cylinders
• Other file types
7 11
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
/bin Common programs, shared by the system, the system administrator and the users. • The central structural concepts of a file system
/dev
Contains references to all the CPU peripheral hardware, which are represented as type are:
files with special properties.
Most important system configuration files are in /etc, this directory contains data
- Boot Block
/etc
similar to those in the Control Panel in Windows - Super Block
/home Home directories of the common users.
/lib
Library files, includes files for all kinds of programs needed by the system and the - Inode List
users.
/sbin Programs for use by the system and the system administrator. - Data Block
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. Boot Block Super Block Inode List Data Blocks
9 13
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• 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
Boot Block Super Block
16 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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
24
Systems Programming 28
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
25
Systems Programming 29
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
26
Systems Programming 30
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
•There must be some way to determine where the Inodes
are, and to keep track of free Inodes and disk blocks. This is Hard Links
done by a Superblock. Superblock is located at a fixed They are the low-level links. It links more than
position in the file system. The Superblock is usually one filename with the same Inode and it
replicated on the disk to avoid catastrophic failure in case of represents the physical location of a file.
corruption of the main Superblock.
When hard link is created for a file, it directly
•Index allocation schemes suffer from some of the same points to the Inode of the original file in the disk
performance problems. As does linked allocation. For space, which means no new Inode is created.
example, the index blocks can be cached in memory, but the Directories are not created using hard links and
data blocks may be spread all over a partition. they can not cross filesystem boundaries. When
the source file is removed or moved, then hard
links are not affected.
Systems Programming 31 Systems Programming 35
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Inode Structure :
2) Soft Links (Symbolic Links)
Soft links are very common. It represents a virtual or abstract
location of the file. It is just like the shortcuts created in
Windows. A soft link doesn't contain any information or
content of the linked file, instead it has a pointer to the
location of the linked file. In other words, a new file is created
Inode Structure :
with new Inode, having a pointer to the Inode location of the
original file.
It is used to create link between directories and can cross file
system boundaries. When the source file is removed or
moved, then soft links are not updated.
We'll study in deep about both the links how to create it and
remove it.
Inode Table
The Inode table contains all the Inodes and is created
when file system is created. 1. ln data/ foo.txt input_files
2. Links provide some protection against accidental
The df -i command can be used to check how many deletion
inodes are free and left unused in the file system.
3. Because of links, we don’t need to maintain two
programs as two separate disk files.
Inode Number
37
Systems Programming 33
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
38
Systems Programming 34
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
How do inodes locate files?
pete@icebox:~$ ls -li
140 drwxr-xr-x 2 pete pete 6 Jan 20 20:13 Desktop
141 drwxr-xr-x 2 pete pete 6 Jan 20 20:01 Documents
2
Systems Programming 47
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
48 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
49 4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• 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.
Course Name : •
•
The Permission Indicators
While using ls -l command, it displays various information related to file permission as follows −
•
Systems Programming $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 Unix / Linux - File Permission / Access Modes
•
•
Changing Permissions
To change the file or the directory permissions, you use the chmod (change mode) command.
• Changing Group Ownership
• There are two ways to use chmod — the symbolic mode and the absolute mode. • The chgrp command changes the group ownership of a file.
• The basic syntax is as follows −
• Using chmod in Symbolic Mode
• The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode.
• With symbolic permissions you can add, delete, or specify the permission set you want by using the operators in the • $ chgrp group filelist
following table.
• The value of group can be the name of a group on the system or the group ID (GID) of a
• Chmod operator & Description group on the system.
• + Adds the designated permission(s) to a file or directory.
• - Removes the designated permission(s) from a file or directory.
• = Sets the designated permission(s). • Following example helps you understand the concept −
• Here's an example using testfile. Running ls -1 on the testfile shows that the file's permissions are as follows −
• $ls -l testfile
• $ chgrp special testfile
• -rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile • Changes the group of the given file to special group.
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Modes
Unix / Linux - File Permission / Access Modes Unix / Linux - File Permission / Access Modes
•
executed.
The PATH variable specifies the locations in which the shell should look for commands.
Notes:
•
•
Usually the Path variable is set as follows −
$PATH=/bin:/usr/bin • Files with multiple links are counted and written for only
• Here, each of the individual entries separated by the colon character (:) are directories.
• If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, one entry.
a message similar to the following appears −
•
•
$hello
hello: not found
• Block counts are based only on file size
19
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
17 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
df Command Device special files
To display information about /boot file system, • Devices can be accessed via special files. A device special file
df /boot does not use any space on the filesystem. It is only an access
We can display information in various block format. For instance see point to the device driver.
1M-byte blocks, run: • Two types of special files exist: character and block special
df -m files. The former allows I/O operations in character mode
df -m /boot while the later requires data to be written in block mode via
Show statistics about the number of free and used inodes the buffer cache functions.
Pass the -i as follows to display index node (inodes) info: • When an I/O request is made on a special file, it is forwarded
df -i to a device driver. A special file is referenced by a major
df -i -H number, which identifies the device type, and a minor
number, which identifies the unit.
df -i -H -T
22 26
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
34
Systems Programming 30
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
inodes
Advantages of the Unix file System • Disk inodes consists of the following fields
•Hierarchical organization: - file owner identifier
•Robustness: - file type
•Security: . - file access permissions
•Compatibility: - file access times
- number of links to the file
- table of contents for the disk address of data in a file
- file size
35
Systems Programming 31
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
inodes
36
Systems Programming 32
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
42
Systems Programming 38
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
49 53
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Path conversion to an inode
54
Systems Programming 58
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
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
55
Systems Programming 59
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
56
Systems Programming 60
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
2
Systems Programming 62
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
63 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
vi basics
• To write and edit some programs and scripts, we require
editors
Course Name : • UNIX provides vi editor for BSD system – created by Bill
Systems Programming Joy
• Bram Moolenaar improved vi editor and called it as vim
(vi improved) on Linux OS
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
The vi Editor INPUT MODE – ENTERING AND REPLACING TEXT
Insertion of Text at Line Extremes (I and A)
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.
6 10
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
7 11
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
8 12
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
9 13
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
ex MODE – SAVING TEXT AND QUITTING ex MODE – SAVING TEXT AND QUITTING
Saving the Work (:w) Writing Selected Lines
14 18
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
ex MODE – SAVING TEXT AND QUITTING ex MODE – SAVING TEXT AND QUITTING
Saving and Quitting (:x and :wq) Escape to the UNIX Shell (:sh and [Ctrl-z])
15 19
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
ex MODE – SAVING TEXT AND QUITTING ex MODE – SAVING TEXT AND QUITTING
Aborting Editing (:q) Recovering from a Crash (:recover and –r)
16 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
ex MODE – SAVING TEXT AND QUITTING ex MODE – SAVING TEXT AND QUITTING
17 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Command MODE – NAVIGATION Command MODE – NAVIGATION
Movement in the Four Directions (h, j, k and l) Moving to Line Extremes (0, | and $)
22 26
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
23 27
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Example
5b takes the cursor 5 words back
3w takes the cursor 3 words forward
24 28
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
25 29
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Command MODE – EDITING TEXT Command MODE – EDITING TEXT
Editing Text – Deleting lines (dd) Editing Text – Joining Lines (J)
30 34
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Editing Text – Moving Text (p, P) Undoing Last Editing Instructions (u and U)
31 35
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
32 36
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
33 37
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Command MODE – EDITING TEXT cp – COPYING A FILE
Search and Repeat Commands
38 42
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
39 43
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
41 45
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
cut Command paste Command
• Most files don’t contain fixed length lines, so we Joining lines (-s)
have to cut fields rather than columns (cutting fields) Let us consider that the file address book contains the
-d for the field delimiter details of three persons
-f for the field list cat addressbook
cut -d \ | -f 2,3 shortlist | tee cutlist1
paste -s addressbook -to print in one single line
will display the second and third columns of shortlist
and saves the output in cutlist1. here | is escaped to paste -s -d ”| | \n” addressbook -are used in a circular
prevent it as pipeline character manner
46 50
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
cut Command
47 51
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
48 52
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
49
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
IMP Note to Self cp – COPYING A FILE
2 6
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
3 7
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
5 9
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
cut Command cat – DISPLAYING AND CREATING FILES
10 14
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
11 15
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
12 16
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
13 17
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
rm – DELETING FILES cmp – COMPARING TWO FILES
18 22
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
19 23
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
20 24
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
21 25
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
diff – CONVERTING ONE FILE TO OTHER CHANGING FILE PERMISSIONS
26 30
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• Usually we have,
• In a relative manner, specify the changes to the
rw-rw-rw- (octal 666) for regular files current permissions
rwxrwxrwx (octal 777) for directories
• The default is transformed by subtracting the user
• In an absolute manner, specify the final permissions
mask from it to remove one or more permissions
• We can evaluate the current value of the mask as,
$ umask
022
27 31
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• When you create a file, you become its owner (third • chmod only changes the permissions specified in the
column) command line and leaves the other permissions
• Group owner of the file (fourth column) unchanged
• Several users may belong to a single group, but the • Syntax
privileges of the group are set by the owner of the file chmod category operation permission filename(s)
and not by the group members
28 32
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
29 33
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
RELATIVE PERMISSIONS ABSOLUTE PERMISSIONS
Category operation permission • Need not to know the current file permissions
u - user + assign r - read • Set all nine permissions explicitly
g - group - remove w - write • A string of three octal digits is used as an
expression
o - others = absolute x - execute
• The permission can be represented by one octal
a - all (ugo)
digit for each category
• For each category, we add octal digits
34 38
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
35 39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Let initially
• 777 signifies all permissions for all category, but
still we can prevent a file from being deleted
-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart
• 000 signifies absence of all permissions for all
chmod go-r xstart category, but still we can delete a file
37 41
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
PERMISSIONS DIRECTORY PERMISSIONS
42 46
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• Let the default permission for the file xstart is • On BSD and AT&T systems
• Kumar – owner (user)
-rw-r--r--
• Metal – group owner
• chmod u-rw, go-r xstart or
• If sharma copies a file of kumar, then sharma will
• chmod 000 xstart become its owner and he can manipulate the
---------- attributes
• This is simply useless but still the user can • chown and chgrp
delete this file • On BSD, only system administrator can use chown
• On other systems, only the owner can change both
43 47
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
44 48
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
we can also specify a character position with in a field to be the beginning of sort
as shown above (sorting on columns).
51 55
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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
52 56
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
It can sort the tasks by CPU usage, memory usage and runtime. can be
better configured than the standard top from the procps suite.
58 2
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
59 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Commands : grep
• Pattern matching and Shell Meta characters
grep Command
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
grep Command grep Command
grep : searching for a pattern • When grep is used with multiple filenames, it
grep options displays the filenames along with the output
Basic regular expressions (BRE)
An introduction
grep “director” emp1.lst emp2.lst
The character class
The *
The dot Where it shows filename followed by the contents
Specifying pattern locations Metacharacters
6 10
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• It scans the file / input for a pattern and displays -i ignores case for matching
lines containing the pattern, the line numbers or -v doesn’t display lines matching expression
filenames where the pattern occurs
-n displays line numbers along with lines
-c displays count of number of occurrences
• It’s a command from a special family in UNIX for -l displays list of filenames only
handling search requirements
7 11
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
14 18
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• It is tedious to specify each pattern separately * Zero or more occurrences of the previous character
with the -e option
• grep uses an expression of a different type to g* nothing or g, gg, ggg, etc.
match a group of similar patterns
• if an expression uses meta characters, it is grep “[aA]gg*[ar][ar]wal” emp
termed a regular expression
• Some of the characters used by regular
Notice that we don’t require to use –e option three
expression are also meaningful to the shell
times to get the same output!!!!!
15 19
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
16 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• grep supports basic regular expressions (BRE) Most of the regular expression characters
by default and extended regular expressions are used for matching patterns, but there are two
(ERE) with the –E option that can match a pattern at the beginning or end
of a line
• A regular expression allows a group of
characters enclosed within a pair of [ ], in which ^ for matching at the beginning of a line
the match is performed for a single character in $ for matching at the end of a line
the group
17 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
grep Command The ERE set
23 27
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
24 28
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
31 35
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
33 37
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Examples Shell Scripts/Shell Programs
38 42
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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.
39 43
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
40 44
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
commands to be executed based previous results Note: Here the script neither requires a executable
permission nor an interpreter line.
41 45
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Read: Making Scripts Interactive Using Command Line Arguments
#! /bin/sh
• Shell’s internal tool for making scripts interactive echo “Program Name : $0”
• Used with one or more variables. echo “No of Arguments : $#”
• Inputs supplied with the standard input are read echo “Arguments are : $*”
into these variables.
Ex: read name $ chmod +x 2.sh
causes the script to pause at that point to take $ 2.sh A B C
input from the keyboard. o/p Program Name : 2.sh
No of Arguments : 3
Arguments are : A B C
46 50
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
47 51
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
48 52
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Course Name :
Systems Programming
Shell Scripting
49
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
IMP Note to Self Using Command Line Arguments
2 6
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
3 7
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
#!/bin/bash
Current Session CS09 echo "Hello, Student”
▪ Decision making constructs
▪ Shell scripts with more examples # This script displays the date, time, username and
▪ Conditional structure # current directory.
echo "Date and time is "
date
echo
echo -e "Your username is: `whoami` \n"
echo -e "Your current directory is: \c"
pwd
4 8
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• Shell scripts are executed in a separate child shell # If there is more than one word in the input, each word can be assigned
process which may or may not be same as the login shell. 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“
5 9
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Shell Scripts Starting
# Script to print user information who currently login , current date & time $ echo '#!/bin/sh' > my-script.sh
#
$ echo 'echo Hello World' >> my-script.sh
clear
echo -e "\nHello $USER" $ chmod 755 my-script.sh
echo -e "\nToday is \c ";date $ ./my-script.sh
echo -e "\nNumber of user login : \c" ; who | wc -l Hello World
echo -e "\nCalendar\n" $
cal
# declaration and printing of string variable • Note that to make a file executable, you must set the
#!/bin/bash eXecutable bit, and for a shell script, the Readable bit
x='Beautiful World' must also be set:
echo $x
echo x # just string 'x' • chmod a+rx first.sh
10
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
#!/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 :- $* "
11
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
Variables
#var.sh
#!/bin/sh
MY_MESSAGE="Hello World"
SOME SIMPLE SCRIPTS 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 # var3.sh
#!/bin/sh #!/bin/sh
echo "What is your name?"
echo What is your name?
read USER_NAME
read MY_NAME echo "Hello $USER_NAME"
echo "Hello $MY_NAME - hope you're well." echo "I will create you a file called ${USER_NAME}_file"
touch "${USER_NAME}_file"
• MY_NAME is a variable
• read helps to read the value from console • The touch command changes attriobutes of a file and
creates a new file of 0 bytes if it does not exist
• echo is used to echo the value on console
• Note the use of {} arounf the variable name to separate it
• $ sign is used to signify a variable from text.
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
Export *
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
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
SOME MORE CONCEPTS This delimiter may be used in a shell script as follows:
You have seen the for simple decision you can use && and ||. If statements need to
be considered only for more complex decisions.
30
Systems Programming 26
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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.
27 31
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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”
29 33
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Using test and [] to evaluate
Shell Script
expressions
# if ... elif ... else
#!/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
34 38
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
#!/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
35 39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
if rm $1
then
echo "$1 file deleted"
fi
36 40
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
42 46
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
43 47
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
44 48
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
45 49
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
expr – Computation and String handling expr – String Handling
50 54
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
51 55
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
expr – String Handling 2) What will be the output of the following script if the variable
num is set to 15?
num=15
if [ $num -lt 10 ]; then
echo "Number is less than 10"
elif [ $num -gt 10 ] && [ $num -lt 20 ]; then
echo "Number is between 10 and 20"
else
echo "Number is 20 or more"
fi
a) Number is less than 10
b) Number is between 10 and 20
c) Number is 20 or more
d) Syntax error
Answer : b
53
57
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
3) Consider the following case statement. What will be the output ANSWER
if the user inputs "y"?
#!/bin/bash
read -p "Continue? (y/n): " answer file="example.txt"
case $answer in
y|Y) echo "Continuing...";; if [ ! -e "$file" ]; then
n|N) echo "Stopping...";; echo "File does not exist. Creating $file..."
touch "$file"
*) echo "Invalid input";; fi
esac if [ ! -s "$file" ]; then
echo "This is a new file" > "$file"
a) Continuing... echo "Added text to new file."
b) Stopping... else
echo "File is not empty. Appending date and time..."
c) Invalid input echo "$(date)" >> "$file"
d) Syntax error fi
Answer : a echo "Displaying contents of $file:"
cat "$file"
58 62
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Which of the following correctly tests if a number stored in var IMP Note to Self
is either greater than 100 or less than 10?
63
59
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
60
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
2
61
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
IMP Note to Students
It is important to know that just login to the session does not
guarantee the attendance.
Once you join the session, continue till the end to consider you
as present in the class.
IMPORTANTLY, you need to make the class more interactive by
responding to Professors queries in the session.
Whenever Professor calls your number / name ,you need to
respond, otherwise it will be considered as ABSENT
3
Systems Programming 7
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Systems Programming 12
BITS Pilani, Pilani Campus BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
More for ..
#for2.sh
#!/bin/sh
for i in hello 1 * 2 goodbye
do
echo "Looping ... i is set to $i"
done
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
Loops - while
#while1.sh
#!/bin/sh
INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
echo "Please type something in (bye to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956
25
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 Systems Programming - V 3.0 BITS Pilani, Pilani Campus
26
Break and Continue
Break
• There are some situations where we want to jump out of a loop instantly,
without wanting to get back to control-command.
• The keyword break allows us to do this.
• When the keyword break is encountered inside any loop, control automatically
passes to the first statement after the loop.
• A break is usually associated with if.
• The loop comes to end on execution of break.
Continue
• In some situations we want to take the control to the beginning of the loop,
bypassing the statements inside the loop which have not yet been executed.
• The keyword continue allows us to do this.
• When the keyword continue is encountered inside the loop, control
automatically passes to the beginning of the loop.
• A continue is usually associated with and if.
for loop for command line arguments
BITS Pilani,
BITS Pilani, Deemed to be University under Section PilaniAct,
3 of UGC Campus
1956 4 Ja n 2 0 1 4 Prepa red f o r W I LP BITS Pilani, Pilani Campus
You can break out of a for loop using 'break' Shell script program to find factorial of a positive
integer N (take N from the user). fact(N)=1×2×…..×N
command as shown below
Using for loop
Example adds "(WEEKEND)" to Sat and Sun, and Script to print the first N numbers in Fibonacci series
"(weekday)" to rest of the days. Given, f0=0, f1=1, and fn=fn‐1+fn‐2 for all n>=2, N is taken from
the user by using read command, for loop
echo "Input N"
clear read N
i=1 fib0=0
fib1=1
for day in Mon Tue Wed Thu Fri Sat Sun fib2=1 O/P
do Input N
if [ $N -lt 0 ]
5
echo -n "Day $((i++)) : $day" then 0
echo "Wrong arg" 1
if [ $i -eq 7 -o $i -eq 8 ]; then exit 1 1
continue; O/P fi 2
Day 1 : Mon (weekday) for ((i=0; i<N; i++)) 3
fi Day 2 : Tue (weekday) do
echo " (weekday)" Day 3 : Wed (weekday) echo "$fib0 "
Day 4 : Thu (weekday) fib0=$fib1
done Day 5 : Fri (weekday)
fib1=$fib2
Day 6 : Sat (WEEKEND)
Day 7 : Sun (WEEKEND)
fib2=`expr $fib0 + $fib1`
28 done 32
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
35 39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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
36 40
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Take start range as N and end range as M from user Files using Shell Scripting
• Find all prime numbers between N and M
Method I
echo "Enter the start line number:”
read startNum
echo “Enter the number of lines to be
displayed:”
read numLine
endLine=$((startNum + numLine – 1))
head ‐n$endLine integernos.txt | tail
‐n$numLine >
37 41
Systems Programming - V 3.0 BITS Pilani, Pilani Campus datanew.txt Systems Programming - V 3.0 BITS Pilani, Pilani Campus
38 42
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
set and shift: Manipulating the Positional
Files using Shell Scripting Parameters
43 47
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
45 49
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
46 50
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
awk
awk is a powerful text-processing tool in
Unix/Linux. It is used for pattern scanning and
Course Name : processing.
Systems Programming 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 5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
O/P:
A Gautam Developer
Chandrashekhar Manager
2 Rajeev Designer 6
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Agenda
getopts
getopts is a built-in shell function used to parse
awk command-line options. Here is example f1.sh
#!/bin/bash
getopts
while getopts "a:b:c" opt; do
automation using shell case $opt in
crontab a) echo "Option a with value: $OPTARG" ;;
b) echo "Option b with value: $OPTARG" ;;
at command for scheduling
c) echo "Option c selected" ;;
\?) echo "Invalid option: -$OPTARG" ;;
esac
4
done 8
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
getopts Automation Using Shell
getopts: This built-in command is used to parse command-line $BACKUP_DIR/backup_$(date +%F_%T).tar.gz: The backup file is
options. It reads options and their arguments, one by one, from saved in the directory specified by BACKUP_DIR.
the command line. The filename is backup_$(date +%F_%T).tar.gz, where:
$(date +%F_%T) generates a timestamp using the date
"a:b:c": The string "a:b:c" specifies the valid options: command.
a:: Option a requires an argument (indicated by the colon : after a). %F produces the date in YYYY-MM-DD format.
b:: Option b also requires an argument. %T produces the time in HH:MM:SS format.
c: Option c does not require an argument (no colon after c).
The final backup file will have a name like backup_2024-08-
opt: This variable stores the current option being processed. 24_15:30:01.tar.gz.
/path/to/data: This is the path to the directory or files you want
The while loop will continue to process options until all options to back up. Replace /path/to/data with the actual directory or
from the command line are parsed. files you need to back up.
Systems Programming 9 Systems Programming 13
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
getopts crontab
Execute the following command crontab is used to schedule recurring tasks.
./f1.sh -a 10 -b 20 –c Example 1: Run a Script Every Day at 2 AM
Edit crontab file
O/P: crontab –e
Option a with value: 10 Add the following line:
Option b with value: 20 0 2 * * * /path/to/script.sh
Option c selected
10 14
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
17 Systems Programming 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Script 3
Script to demonstrate the useage of Array Variables
Advanced Example: monitor.sh
###Script to demonstrate the usage of Array Variables
df /: The df command reports the disk space usage of ###Defining the array variables individually
name[0]=Smith
file systems. df / checks the root ("/") file system. name[1]=Steve
grep /: Filters the output to include only the line name[2]=Rohit
### Accessing the variables
containing the root file system. echo 'echo ${name[0]}='${name[0]}
awk '{print $5}': Extracts the fifth column, which echo 'echo ${name[1]}='${name[1]}
echo 'echo ${name[2]}='${name[2]}
represents the percentage of disk space used. ### Accessing all values at a time
echo 'echo ${name[*]}='${name[*]}
sed 's/%//g': Removes the percentage symbol (%) from echo 'echo ${name[@]}='${name[@]}
the value so that it can be compared as an integer. ### To get the array size
echo 'echo ${#name[*]}='${#name[*]}
echo 'echo ${#name[@]}='${#name[@]}
19 Systems Programming 23
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
echo "Disk usage is critically high: $DISK_USAGE%": Prepares the ###Script to check the type of file
#!/bin/bash
message body, including the current disk usage percentage. ###File test using if--else statement
FILE='/dev/sda'
if [ -c $FILE ]; then
echo "$FILE is a character special file"
mail -s "Disk Usage Alert" [email protected] else
echo "$FILE is not a character special file"
pilani.ac.in: Sends an email with the subject "Disk Usage Alert" to fi
*/30 * * * *: This crontab entry means the script will run every 30 fi
if [ -d $FILE ]; then
minutes. echo "$FILE is a directory"
else
echo "$FILE is not a directory"
fi
/path/to/monitor.sh: Replace this with the actual path to your
20 Systems Programming 24
script.
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Script 5 Files using Shell Scripting
###Option parsing using GETOPTS
#!/bin/bash
###Option Parsing using GETOPTS
Task
if [ "$#" -ne "6" ]; then
echo "Invalid Parameters" • Copy numLine number of lines from the
exit 1
fi
while getopts a:b:c: var >/dev/null 2>&1
starting line number startNum of the file
do
case $var in
a) a=$OPTARG;;
named data.txt
b) b=$OPTARG;;
c) c=$OPTARG;; • Store the copied lines in a file named
*) echo Invalid Suffix ; exit 1;;
done
esac
datanew.txt
echo "Values given to suffix a = $a"
echo "Values given to suffix b = $b"
• Take numLine and startNum as user input
echo "Values given to suffix c = $c"
Systems Programming 25 29
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Script 6
Shell script for counting the total number of lines across a set of files. Files using Shell Scripting
#!/bin/bash
Method I
echo "Enter the start line number:”
# Counting the number of lines in a list of files
# for loop over arguments
if [ $# -lt 1 ]
then
echo "Usage: $0 file ..." read startNum
exit 1
fi
echo "$0 counts the lines of code"
echo “Enter the number of lines to be
l=0
n=0
displayed:”
s=0
for f in $*
do
read numLine
endLine=$((startNum + numLine – 1))
l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
echo "$f: $l"
n=$[ $n + 1 ]
Done
s=$[ $s + $l ]
head ‐n$endLine integernos.txt | tail
echo "$n files in total, with $s lines in total"
‐n$numLine >
Systems Programming 26 30
BITS Pilani, Pilani Campus datanew.txt Systems Programming - V 3.0 BITS Pilani, Pilani Campus
27 31
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
28 32
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Files using Shell Scripting shift: Shifting Arguments left
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
33 37
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
34 38
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
35 39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
36 40
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Why we need protection? fscanf system call execution
To prevent the access of unauthorized users
To ensure that each active programs or processes in
the system uses resources only as the stated policy
To improve reliability by detecting latent errors
In single task / programming environment
– To protect OS from incorrect program
In multiprogramming / multitasking environment
– To protect OS and other programs from
incorrect program
41 45
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
42 46
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls are needed for all the services that need
resources.
43 47
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls
44 48
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Steps for Making a System Call Examples of System Calls
(Example: read call)
A system call is implemented by a ``software interrupt'' that
transfers control to kernel code; • Example:
in Linux/i386 this is ``interrupt 0x80''. The specific system call – getuid() //get the user ID
being invoked is stored in the EAX register, and its arguments are
held in the other processor registers. – fork() //create a child process
In our example, the number associated to read is __NR_read, – exec() //executing a program => execve (2)
defined in <asm/unistd.h>.
in Linux
After the switch to kernel mode, the processor must save all of its
registers and dispatch execution to the proper kernel function, • Don’t confuse system calls with libc calls
after checking whether EAX is out of range.
– Differences?
The system call we are looking at is implemented in the sys_read
function. – Is printf() a system call?
The read finally performs the data transfer and all the previous – Is rand() a system call?
steps are unwound up to the calling user function. 49 53
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Why do you need system calls in User mode and Kernel mode Switching
Operating System?
There are various situations where you must require system calls in The User mode is normal mode where the process has limited
the operating system. access. While the Kernel mode is the privileged mode where
the process has unrestricted access to system resources like
hardware, memory, etc. A process can access I/O Hardware
It is must require when a file system wants to create or delete a registers to program it, can execute OS kernel code and access
file. kernel data in Kernel mode. Anything related to Process
Network connections require the system calls to sending and management, IO hardware management, and Memory
receiving data packets. management requires process to execute in Kernel mode.
If you want to read or write a file, you need to system calls.
If you want to access hardware devices, including a printer, This is important to know that a process in Kernel mode get
scanner, you need a system call. power to access any device and memory, and same time any
System calls are used to create and manage new processes. crash in kernel mode brings down the whole system. But any
crash in user mode brings down the faulty process only.
51 55
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
52 56
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Use of A System Call to Perform I/O Types of System Calls
Process Control
Process control is the system call that is used to direct the
processes. Some process control examples include creating,
load, abort, end, execute, process, terminate the process,
etc.
File Management
File management is a system call that is used to handle the
files. Some file management examples include creating
files, delete files, open, close, read, write, etc.
57 61
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Information Maintenance
Information maintenance is a system call that is used to maintain
information. There are some examples of information maintenance,
including getting system data, set time or date, get time or date, set
system data, etc.
Communication
Communication is a system call that is used for communication. There
are some examples of communication, including create, delete, etc.
58 62
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process Process
fnCall() sysCall()
OS
60 64
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls ‐ open System call program example
65 69
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – creat, close File related system calls – lseek
66 70
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – read File related system calls – lseek
67 71
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – write File related system calls – mkdir, rmdir
68 72
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – rename • System calls related to process
– fork
– wait
– exec
– exit
– signal
– kill
– raise
73
77
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
74 78
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – symlink Process related system calls – fork
75 79
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – unlink Process related system calls – fork
76 80
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
#include <stdio.h>
Process related system calls – fork #include <sys/types.h>
#include <unistd.h>
Calling fork()
int main()
{
pid_t p;
p = fork();
if(p==-1)
{
printf("There is an error while calling fork()\n");
}
if(p==0)
{ OUTPUT:
printf("We are in the child process\n"); sysads@linuxhint $ gcc fork.c -o fork
} sysads@linuxhint $ ./fork
else We are in the parent process
We are in the child process
{
printf("We are in the parent process\n");
}
return 0;
81 } 85
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
82 86
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Calling fork()
Calling fork()
Consider the following example in which we have used the fork() system call to create
a new child process:
84 88
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Agenda
System calls
System calls for Process management
Execution of system calls
Thank You
89 4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System Call
Course Name :
Systems Programming
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
2 6
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
3 7
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – creat, close File related system calls – lseek
8 12
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – read File related system calls – lseek
9 13
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – write File related system calls – mkdir, rmdir
10 14
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
11 15
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – link Process related system calls – fork
16 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – symlink Process related system calls – fork
17 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – unlink Process related system calls – fork
18 22
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
24 28
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Calling fork()
Process related system calls – wait
#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;
} 25 29
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
32 36
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
33 37
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
helloexec.c
Process related system calls – exec
#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
34 38
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
35 39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – exit Process related system calls – signal
40 44
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – exit Process related system calls – signal
#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;
else
int status;
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);
} 41 45
}
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – exit Process related system calls – signal
Output:
42 46
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal Process related system calls – signal
43 47
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal Process related system calls – kill & raise
48 52
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal 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.
49 53
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal 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;
}
50 54
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – kill 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.
51 55
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
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 Course Name :
and new file descriptors may be used interchangeably. Systems Programming
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.
56
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
58 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
59 4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Software The Compiler job 2 – VALIDATION
5 9
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• System software is computer software designed to • Tries to produce as good a target program as it can
operate the computer hardware and to provide a • Criterion for goodness could be
platform for running application software. 1. How fast the target program runs (most common)
• Examples : OR
– Loaders 2. Consumption of power and/or memory
– Assembler
• Differences among compilers depends on
– Linkers
• Their source and target languages,
– Operating system
as well as
– Compilers
• on the relative importance of these three jobs
– Editors
6 10
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Compiler
Systems Programming 11
Systems Programming 7
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
15 Systems Programming 19
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Converts Assembly L1
X
202
204
Systems Programming 25
Systems Programming 21
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Systems Programming 24 28
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Basic Definition We Need…three Processes
Loading - which allocates memory location and brings the •Loading - which allocates memory location and brings the object
object program into memory for execution - (Loader) program into memory for execution
•Relocation - which modifies the object program so that it can be
Linking- which combines two or more separate object loaded at an address different from the location originally
programs and supplies the information needed to allow specified.
references between them - (Linker) •Linking- which combines two or more separate object programs
and supplies the information needed to allow references between
Relocation - which modifies the object program so that it can them
be loaded at an address different from the location originally
specified - (Linking Loader) •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.
29 33
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Code
Loader
30 34
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Bootstrap Loaders
• Source Program – Assembly Language How is the loader itself loaded into the memory ?
• Object Program - From assembler
• Contains translated instructions and data values from
the source program • When computer is started – with no program in memory,
• Executable Code - From Linker a program present in ROM ( absolute address) can be
made executed – may be OS itself or A Bootstrap loader,
• Loader - Loads the executable code to the specified which in turn loads OS and prepares it for execution.
memory locations and code gets executed.
• The first record ( or records) is generally referred to as a
bootstrap loader – makes the OS to be loaded
• Such a loader is added to the beginning of all object
programs that are to be loaded into an empty and idle
system
31 35
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
32 36
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Problems linker must solve Assembling
37
Systems Programming 41
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Pre-Processing
1. Comments Removal,
2. Macros Expansion,
3. File inclusion
Systems Programming 39 Systems Programming 43
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
JVM Interpreter/JIT
Compiler Bytecode Verifier Class Loader Subsystem
(Interprets bytecode (Ensures bytecode is (Loads .class files into
or compiles it into | | valid and secure) memory)
native machine code
for execution)
Runtime Environment
| | (Includes memory
Execution Engine | | management, Output
(Manages execution of garbage | | collection, (Console/GUI)
bytecode) thread management,
Systems Programming 40 Systems Programming 44
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Linkage Editors
•Source Code:
•You write the Java program in a .java file. Object
•Compilation: Program (s)
•The Java compiler (javac) compiles the .java file to a .class file
containing bytecode. Linkage
•Bytecode: Library editor
Write an assembly language program to find the sum of two numbers using LC3
and assemble, load and execute the same using the LC3Simulator. Dynamic Linking
Step1:Write the program in Linux using vi editor and save it as sum.asm • Linkage editors perform linking before the program is
Program: loaded for execution.
• Linking loaders perform these same operations at
.ORIG x3000 ; Starting address of the program
; Load the first number into register R0
LD R0, NUM1 load time.
; Load the second number into register R1
• Dynamic linking postpones the linking function until
LD R1, NUM2 execution time.
; Add the contents of R0 and R1, store the result in R2 – A subroutine is loaded and linked to the test of the
ADD R2, R0, R1 program when it is first called.
; Store the result from R2 into memory location SUM
ST R2, SUM
Object
The source
• Dynamic linking is often used to allow several executing
Program(s)
program is first programs to share one copy of a subroutine or library.
assembled or
compiled,
producing an
• For example, a single copy of the standard C library can
Library Linking
object program. A
loader linking loader
performs all be loaded into memory.
linking and loading
operations, and
loads the program
Memory into memory for • All C programs currently in execution can be linked to
execution
this one copy, instead of linking a separate copy into
each object program.
Processing of an Object program using LL
48 52
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Swapping
Dynamic Linking Application
53
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Swapping (Cont.)
Dynamic Linking Advantage
• Allow several executing programs to share one copy of • Does the swapped out process need to swap back in
a subroutine or library to same physical addresses?
• In an object oriented system, dynamic linking makes it • Depends on address binding method
possible for one object to be shared by several – Plus consider pending I/O to / from process
programs memory space
• Modified versions of swapping are found on many
• However, without using dynamic linking, these systems (i.e., UNIX, Linux, and Windows)
subroutines must be loaded and linked every time the – Swapping normally disabled
program is run. – Started if more than threshold amount of memory
• Using dynamic linking can save both space for storing allocated
the object program on disk and in memory, and time – Disabled again once memory demand reduced
below threshold
for loading the bigger object program.
54
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
55
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• The OS examines its internal tables to determines whether • Main memory must support both OS and user
the subroutine is already loaded. processes
• If needed, the subroutine is loaded from the library. • Limited resource, must allocate efficiently
• Then control is passed from the OS to the subroutine being • Contiguous allocation is one early method
called.
• Main memory usually into two partitions:
• When the called subroutine completes its processing, it
returns to its caller (operating system). – Resident operating system, usually held in
• The OS then returns control to the program that issues the low memory with interrupt vector
request. – User processes then held in high memory
• After the subroutine is completed, the memory that was – Each process contained in single contiguous
allocated to it may be released.
section of memory
56
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Contiguous Allocation (Cont.)
Causes of Fragmentation
Systems Programming 66
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• First-fit: Allocate the first hole that is big enough • When a process is allocated to a memory block, and if the
process is smaller than the amount of memory requested, a
• Best-fit: Allocate the smallest hole that is big enough; must search free space is created in the given memory block. Due to this,
entire list, unless ordered by size the free space of the memory block is unused, which
– Produces the smallest leftover hole
causes internal fragmentation.
• Worst-fit: Allocate the largest hole; must also search entire list • For Example:
– Produces the largest leftover hole • Assume that memory allocation in RAM is done using fixed
partitioning (i.e., memory blocks of fixed sizes). 2MB, 4MB,
First-fit and best-fit better than worst-fit in terms of speed and storage 4MB, and 8MB are the available sizes. The Operating System
utilization
uses a part of this RAM.
Systems Programming 67
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Fragmentation
External Fragmentation
Systems Programming 72 76
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
C as a System Programming Language
Systems Programming 5
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
2
Systems Programming 6
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
3 Systems Programming 7
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• Functions are an essential component of the C programming // C program to illustrate inbuilt function
language. They help you divide bigger problems into smaller, more // Header file for printf function
manageable chunks of code, making it simpler to create and run #include <stdio.h>
programs.
• A function is a block of code that executes a particular task in // Driver Code
programing. It is a standalone piece of code that can be called from int main()
anywhere in the program. {
• The function contains the set of programming statements enclosed // Library function printf
by {}. printf(“Hello Everyone!");
• A function can be called multiple times to provide reusability and return 0;
modularity to the C program. }
Function Calling
• In this example, the sum_Numbers function is declared with a
After defining the function definition, we need to call the defined function in a
program to execute its tasks. However, a function can be called multiple times
function statement at the top of the file, which specifies its
by writing the function name followed by arguments lists. name, return type (int), and parameters (x and y, both are of
Syntax: int type).
function_name(arg1, arg2, ...) • The actual code for the sum_Numbers function is defined in
Here, arg1, arg2 are the actual arguments passed to the function_name. the function definition. Here, the function simply adds its two
Function Declaration parameters and returns the result.
The function declaration defines the function name, return type and the passed • The main function calls the sum_numbers function with
arguments in it. A function definition is always defined outside of the main() arguments , and stores the result in the result variable. Finally,
function in any C program.
it prints the result using the printf function.
Syntax:
return_type function_name ( data_type arg1, data_type arg2, ..) ;
return 0; Example: multiply(), sum() divide(), etc. are the Exemple: printf(), sqrt(), strcpy(), etc.
user defined or user created function in a
} Systems Programming program. Systems Programming
19 23
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• In this example, the func function is declared with a function • Protection refers to a mechanism which controls the access of
statement at the top of the file, which specifies its name, programs, processes, or users to the resources defined by a
return type (int), and parameters (radius of int type). computer system.
• The actual code for the func function is defined in the • We can take protection as a helper to multi programming
function definition. Here, the function calculate the area of operating system, so that many users might safely share a
the circle using basic formula and returns the result. common logical name space such as directory or files.
• CPU protection
– Prevent a user from using the CPU for too long
• Throughput of jobs, and response time to events (incl.
user interactive response time) Privileged Instruction Examples
• Memory protection • Memory address mapping
• Data cache flush and invalidation
– Prevent users from modifying kernel code and data • Invalidating TLB entries
structures • Loading and reading system registers
This is important to know that a process in • Changing processor mode from kernel to
– …and each others code and data Kernel mode get power to access any user
• I/O protection device and memory, and same time any
crash in kernel mode brings down the
• Changing the voltage and frequency of the
processor
– Prevent users from performing illegal I/O’s whole system. But any crash in user mode • Halting a processor
brings down the faulty process only. • Reset a processor
Systems Programming
• I/O operations
25
Systems Programming 29
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
To prevent the access of unauthorized users • System calls have always been the means through which
user space programs can access kernel services.
To ensure that each active programs or processes in the system
uses resources only as the stated policy
• System call is the only legal entry point to the kernel.
• System call provides an abstract hardware interface for
To improve reliability by detecting latent errors
user space
In single task / programming environment • Application need not worry about type of disk, media
– To protect OS from incorrect program and file system in use.
In multiprogramming / multitasking environment
– To protect OS and other programs from incorrect
program
26 30
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
The User Mode and The Kernel Mode How System Call Works?
• There are two modes available in a computer system: the kernel mode
and the user mode.
• In the computer system, various types of programs or apps are executed
on a computer system. Programs have direct access to hardware
resources and memory in kernel mode, which is more privileged than
user mode.
• In user mode, programs are unable to access memory and hardware
resources directly. Most programs run in the user mode.
• A program sends a system call request to the kernel when it needs a
hardware resource and memory. Following that, the mode changes
from user mode to kernel mode.
• When the work is finished, the mode switches back to user mode from
kernel mode. As a result, this mode transition is also known as context
switching. Systems Programming 28
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
System calls / library calls Examples
How System Call Works?
• Steps Each I/O system call has corresponding procedure calls from
– Step 1) The processes executed in the user mode till the time the standard I/O library.
a system call interrupts it.
System calls Library calls
– Step 2) After that, the system call is executed in the kernel-
mode on a priority basis. open Fopen
– Step 3) Once system call execution is over, control returns to close Fclose
the user mode., read fread, getchar, scanf, fscanf,
– Step 4) The execution of user processes resumed in Kernel getc, fgetc, gets, fgets
mode. write fwrite, putchar, printf, fprintf
putc, fputc, puts, fputs
lseek fseek
37
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Why do you need system calls in Operating System Calls versus Function Calls
System?
Function Call System Call
There are various situations where you must require system calls in
the operating system.
Process Process
It is must require when a file system wants to create or delete a
file. fnCall() sysCall()
Differences between the System Call and Library Examples of System Calls
Call
1. A system call is a kernel function that allows you to enter kernel mode
and access a hardware resource. On the other hand, a library call is a • Example:
function provided by a programming library to complete a task. – getuid() //get the user ID
2. The mode switches from user to kernel mode in the system call function. – fork() //create a child process
On the other hand, there is no mode switching in the library call
function. – exec() //executing a program => execve (2)
3. The system call takes longer to execute than the library call. On the other in Linux
hand, the library call is faster to execute than the system call.
• Don’t confuse system calls with libc calls
4. All functions are part of the kernel in the system call. On the other hand,
all library functions in a library call are part of the programming – Differences?
language's standard library file. – Is printf() a system call?
5. It is a program's request to access a process in kernel mode. On the – Is scanf() a system call?
other hand, a library call is a program's request to access a library
function provided in a programming library.
Systems Programming 35 39
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
#include <syscall.h>
• A system call is executed in kernel space, whereas a library call #include <unistd.h>
is executed in user space. #include <stdio.h>
• A library call is a function given by programming libraries. In #include <sys/types.h>
contrast, a system call is a kernel function that allows you to int main(void)
enter kernel mode and access a hardware resource. {
• Library calls may rely on the system calls to finish the task. long ID1, ID2;
ID1 = syscall(SYS_getpid); /* direct system call SYS_getpid (func no. is 20) */
• Some instances of system calls are cd(), fork(). Some examples printf ("syscall(SYS_getpid)=%ld\n“,ID1); /* "libc" wrapped system call
of library calls are fopen(), fprintf (). SYS_getpid (func no. is 20) */
ID2 = getpid();
printf ("getpid()=%ld\n", ID2);
return(0);
}
Systems Programming 36 40
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Types of System Calls Communication System Call
41 Systems Programming 45
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
– File offset: The byte position in the file where the next I/O
operation through that open file description begins
• Each open file description associated with a regular file, block special
file, or directory has a file offset
• There is no file offset specified for a pipe or FIFO (described later)
• Important points
– A file descriptor does not describe a file
• It is just a number that is ephemerally associated with a particular
open file description
– The description of the file is in the inode
• There may be several different open file descriptors (or none)
referring to a file at any given time.
• Including Inode table, the kernel also contain two other data Implication of the file descriptor/open file
structures, the file table and the user file descriptor table. descriptions/inode table organization in UNIX
• The file table is a global kernel structure, but the user file – open and creat
descriptor is allocated per process. • search for the first empty slot in the process file descriptor table
• When a process opens or creates a file, the kernel allocates an • allocate an open file description in the file table, which has a
entry from each table, corresponding to the file’s inode. pointer to the inode table
• Entries in the three structures- user file descriptor table, file – dup and dup2
table, and inode table- maintain the state of the file and the • Duplicate the file descriptor in the process file descriptor table
user’s access to it • Where is the current file position stored?
File Descriptors
• The file table keeps track of the byte offset in the file where the user’s
next read or write will start, and the access rights allowed to the
opening process.
• The user file descriptor table identifies all open file for a process and
their relationship to each other.
• The kernel returns a file descriptor for the open and create system
calls, which is an index into the user file descriptor table.
• When executing read and write system calls, the kernel uses the file
descriptor to access the user file descriptor tables, follows pointers to
the file table and inode table entries, and from the inode, finds the
data in the file.
57 2
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
58 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls
File related system calls
Process related system calls
Execution of system calls
59 4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System Call
• System calls are interfaces provisioned by the
operating system to allow user-level applications to
interact with low-level hardware components & make
Course Name : use of all the services provided by the kernel.
Systems Programming
• Types of System calls:
File System :(open, create, close, read, write, mkdir, …)
Process Control :(fork, wait, exec, exit, signal, kill, …)
Memory Management :(brk, sbrk, mmap, munmap, mlock, …)
Inter-process Communication : (pipe, socket, shmget, ...)
28th SEP 2024 Device Management :(setConsolMode, readConsol, writeConsol, …)
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related System calls - open Ex-1: To read first 10 characters from a file.
int open(const char *filepath, int flags, ,... /* mode_t mod */):
File related system calls – creat, close Ex-1: To read first 10 characters from a file.
int creat(const char *path, mode_t mod): • The operating system assigns internally to each opened file a
• Used to create a new file. descriptor or an identifier (usually this is a positive integer). The
• Returns the file descriptor or -1 in case of an error. value of the file descriptor will always be a positive number
• This call is equivalent with: greater than 2.
open(path, O_WRONLY | O_CREAT | O_TRUNC, mod); • fd=open("test.txt",O_RDONLY): Opens test.txt in read mode
• The argument path specifies the name of the file, while and the file descriptor is saved in integer fd.
mod defines the access rights. • The printf() statement prints the value of the file descriptor.
• If the created file doesn’t exist, a new i-node is allocated • n=read(fd,buff,10): Reads 10 characters from the file pointed
and a link is made to this file from the directory it was by the file descriptor fd and save them in buffer buff.
created in. • write(1,buff,n): Writes the content of the buffer on the screen.
int close(int fd): • <sys/types.h>, <sys/stat.h>, and <fcntl.h> header files are
• Used to close the file. required for open().
• It returns 0 in case of success and -1 in case of an error. • <unistd.h> is required for read write and close.
Systems Programming 7 Systems Programming 11
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
File related system calls – read Ex-2: To copy the contents of an existing file into another file.
File related system calls – write Ex-2: To copy the contents of an existing file into another file.
ssize_t write(int fd, const void* buf, size_t cnt): • This example copies the contents of the file “test.txt” to a new file
named “dup1.txt” using system calls.
• Used for writing a certain number of bytes into a file • Line 10 opens the file “test.txt” in read only mode.
starting from the current position . • Line 11, checks if the file is not opened successfully then prints a
• Returns the number of bytes written, and -1 in case of an message “Error in opening file” and terminates.
error. • Line 16, opens a file “dup1.txt” for writing purpose.
• It writes cnt bytes from the buffer buf into the file that has • O_WRONLY : Opened for writing
as its descriptor fd. • O_CREAT : Creates the file if it doesn't exist, otherwise open for writing.
• O_TRUNC: Truncates the file to zero length if it already exists.
• Line 17, repeats a loop if number of bytes read is more than zero.
The read system call reads specific number of bytes into buffer
from the file referred by the file descriptor.
9
Systems Programming 13
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Ex-2: To copy the contents of an existing file into another file. File related system calls – mkdir, rmdir
• Line 19, writes n byte from buffer into file referred by fd1.
• Line 21, if there is problem in reading from file, otherwise prints
successful message.
• Finally, line 25 and 26 close the files.
• After execution for the copied file “dup1.txt” permission may need
to be changed.
18
Systems Programming 14
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Ex-3
File related system calls – rename
15 19
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – lseek Ex-4: To create, rename and remove a directory
16
Systems Programming 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
File related system calls – lseek File related system calls – link
test1.txt::
abcdefghijklmnop
abcdefghijklmnop
^
O/P: klmno
abcdefghijklmnop
^
O/P: fghij
21
Systems Programming 17
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – symlink Process related system calls – fork
22 26
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
File related system calls – unlink Process related system calls – fork
23 27
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Ex-4: To demonstrate link, symlink and unlink system calls Process related system calls – fork
28
Systems Programming 24
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
30 34
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Calling fork()
Process related system calls – wait
#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;
} 31 35
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Ex-5: To demonstrate fork system calls 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");
o/p:
}
printf("Bye\n");
return 0;
} 37
Systems Programming 33
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
We have two .c files here
Ex-6: To demonstrate wait system call
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;
o/p: }
38 42
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• A pid_t variable named pid is declared to store the process ID #include <stdio.h>
returned by fork(). #include <unistd.h>
• The fork() system call is called, creating a new child process. #include <stdlib.h>
• The return value of fork() is checked to determine whether the int main(int argc, char *argv[])
current process is the child or parent. {
• If the current process is the child, it prints a message and then printf("We are in helloexec.c\n");
exits using return 0. printf("PID of helloexec.c = %d\n", getpid());
• If the current process is the parent, it prints a message and then return 0;
calls wait(&status). } Output :
• The wait() system call suspends the parent process until the child PID of exec.c = 4733
We are in helloexec.c
process terminates. The status argument is used to retrieve PID of helloexec.c = 4733
information about the child process's termination.
39 43
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – exec Ex-7: To demonstrate exec system call
• The exec system call family in C is used to replace the current o/p
process with a new process image. This means that the entire
memory space, program counter, and other process attributes
are replaced with those of the new program.
• 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, • This program replaces the current process with the ls command,
and same file descriptor (because process is not replaced which lists the contents of the root directory.
process image is replaced) • The args array contains the arguments to the ls command, and
• Virtual memory mapping of the current process image is • the envp array is empty, indicating that no environment variables
replaced by virtual memory of new process image. are passed to the new process.
Systems Programming 40 Systems Programming 44
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
• execl(const char *path, const char *arg, ...): Takes a path to the
executable file and a list of arguments, including the program name.
• execlp(const char *file, const char *arg, ...): This function is
similar to execl, but it searches the environment variable PATH to find
the executable file.
• execle(const char *path, const char *arg, ..., char *envp[]):
Takes an additional argument envp, which is an array of environment
variables to be passed to the new process.
• execvp(const char *file, const char *argv[]): This function is The program uses execlp to search the PATH for an executable file
similar to execlp, but it takes an array of arguments instead of individual named ls and passing -l as argument to the new program. The new
strings. program is the same program used by the shell command ls to list
• execve(const char *path, char *argv[], char *envp[]): This files in a directory.
function is the most flexible exec system call, allowing you to specify the
path to the executable, an array of arguments, and an array of
environment variables.
Systems Programming 41 Systems Programming 45
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Ex-9: To demonstrate exec system call
IMP Note to Self
o/p
The program uses execvp to search the PATH for an executable file
named ls and passing -l as argument to the new program. The new
program is the same program used by the shell command ls to list
files in a directory. In comparison to using execv we don’t have to
provide the full path to ls when using execvp, only the name of the
executable. 2
Systems Programming 46
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
47 3
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls
System calls for Process management
System calls for memory management
48 4
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
CS-14 Overview
• What is system call? Types of system calls.
• File Related System calls
• Open, Create, Close, Read, write, lseek, mkdir, rmdir, rename,
Course Name : link, simlink, unlink covered.
• Process Related System calls
Systems Programming
• Fork, wait, exec covered
• We will continue with other process related system calls such
as: exit, signal, kill, raise
5
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – exit Ex-1: exit
• execl("/bin/ls", "ls", "-l", 0): Replaces the current process with the ls
command. The four arguments represent the following: path to the executable
(/bin/ls), executable name, then the arguments for ls command and the last
argument 0 indicate the end of the argument list. If execl() fails (e.g., due to
incorrect path or permissions), it prints an error message and exits.
6
Systems Programming 10
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
8 12
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
• 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.
13
Systems Programming 9
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal 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
14 18
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
15
Systems Programming 19
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Process related system calls – signal Process related system calls – kill
16 20
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Process related system calls – signal Process related system calls – kill & raise
17 21
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
Ex-3: kill System calls for IPC: pipe()
• The program demonstrates
the use of the fork system • The header file of pipe() unistd.h
call to create a child process. • The program creates a pipe using the pipe function.
• The child process performs a
simple task (sleeping for 10
• A pipe is a special type of file that allows communication
seconds) and then exits. between processes. It consists of two file descriptors: one for
• The parent process sends an reading and one for writing.
interrupt signal to the child • The pipe function returns an array of two integers, pipefds[0] and
process using kill. pipefds[1], which represent the read and write file descriptors,
• The parent process waits for
the child to terminate using
respectively.
wait and prints its exit status. • The program then prints the values of these file descriptors to
the console.
26
Systems Programming 22
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
27
Systems Programming 23
BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls for IPC: pipe() System calls for IPC: dup()
#include<unistd.h>
The pipe() system function is used to open file #include<stdio.h>
descriptors, which are used to communicate #include<fcntl.h>
between different Linux processes. In short, int main()
the pipe() function is used for inter-process {
communication in Linux. 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);
}
24 28
Systems Programming - V 3.0 BITS Pilani, Pilani Campus Systems Programming - V 3.0 BITS Pilani, Pilani Campus
System calls for IPC: pipe() System calls for IPC: dup()
#include <stdio.h>
#include <stdlib.h> • The program demonstrates the use of the open and dup
#include <unistd.h> functions to open a file and create a duplicate file descriptor.
int main(void) { • The open function creates a new file descriptor and returns
int pipefds[2]; its value.
if(pipe(pipefds) == -1) { • The dup function creates a duplicate file descriptor for an
perror("pipe"); existing open file.
exit(EXIT_FAILURE); • The duplicate file descriptor shares the same file descriptor
} table entry as the original file descriptor, which means they
printf("Read File Descriptor Value: %d\n", pipefds[0]); refer to the same open file.
printf("Write File Descriptor Value: %d\n", pipefds[1]);
return EXIT_SUCCESS;
}
25
Systems Programming 29
Systems Programming - V 3.0 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Memory Management System Calls Memory Management System Calls: mmap
• There are two main system calls to manipulate memory, namely • void *mmap(void *addr, size_t length, int prot, int flags, int fildes,
brk and sbrk. off_t off):
• Both brk and sbrk change the amount of space allocated for the • The mmap system call in Linux provides a powerful and flexible
calling process's data segment. way to map files or devices into the address space of a process.
• They change the process's break value and the operating system • This allows for efficient memory-mapped I/O operations and
adjusts their allocated amount of space accordingly, which may shared memory communication between processes.
be an increase or a decrease or no change. • Parameters are discussed below.
• The break value is the address of the first memory location after
the end of the data segment for the process.
• brk and sbrk are very rarely used because the malloc, calloc, and
free library functions are adequate for allocating and freeing
memory space; brk and sbrk should not be used in a program
that also uses mallocs/calloc and free.
Systems Programming 30 Systems Programming 34
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
o/p
o/p
39
Systems Programming - V 3.0 BITS Pilani, Pilani Campus