LSP Lab Manual 21CSL35A - Students
LSP Lab Manual 21CSL35A - Students
LAB RUBRICS
Continuous Assessment:
Not written 0
Passes all specified test cases efficiently and shown output
3
for possible inputs
Execution &
Fails in some test cases or wrong input and output 2
Results (3)
partial execution 1
1
21CSL35A LINX SYSTEM PROGRAMMING LAB
Answers satisfactorily 1
During the semester, 2 internal tests will be conducted for 20 + 20 =40 marks.
The first 6 programs will be included in the 1st lab internal test and the remaining 6 programs
will be included in 2nd lab internal test
Not written 0
2
21CSL35A LINX SYSTEM PROGRAMMING LAB
Not written 0
COMMAND
A command is an instruction given by the user telling a computer to do something such as run
a single program or group of linked programs. They are generally issued by typing them in the
command line and then pressing the enter key which passes them to the shell. It consists of a
command name followed by one or more strings that comprise options and arguments.
SYNTAX
command <options> <arguments>
The passwd command is used to change the password of a user account. A normal user can
run passwd to change their own password, and a system administrator (the superuser) can use
3
21CSL35A LINX SYSTEM PROGRAMMING LAB
passwd to change another user's password, or define how that account's password can be used
or changed.
Running passwd with no options will change the password of the account running the
command. You will first be prompted to enter the account's current password:
When you enter a password, the string is encrypted by the system. Encryption generates a string
of random characters. This encryption is stored in a file named shadow in the /etc directory
ii) $ who
The who command prints information about all users who are currently logged in.
For example:
$ who
nhce :0 2022-07-10 10:08 (:0)
nhce pts/0 2022-07-11 10:22 (:0)
nhce pt/4 2022-07-11 12:11 (:0)
who –H, who –Hu, who –u, who –uH provides more detailed instruction of who all the users
logged in.
iii) $ who am i
Displays the same information, but only for the terminal session where the command was
issued, for example:
tput command is used to query the terminfo terminal database and check if that terminal
supports a specific feature.
tput command accepts the terminal commands and outputs the control code sequences for that
terminal. Using tput you can control the color and cursor of your terminal.
You can move the cursor to a specific row and column using tput cup. Following example
positions the cursor at row 2 and column 3.
$ tput cup 2 3
4
21CSL35A LINX SYSTEM PROGRAMMING LAB
If you are in middle of the terminal screen, tput clear will clear the screen and put you at the
top of the terminal screen.
$ tput clear
tput allows you to turn on and turn off the text high lighting. When you turn it ton, new text in
the terminal gets bold.
$ tput bold
When you turn it off, new text in the terminal returns to normal display.
$ tput sgr0
In the below example, it bolds the particular text ‘guide’ by turning on and turning off
highlighting accordingly.
$ tput smul
$ tput rmul
In the below example, it underlines the ‘guide’ text by using smul and rmul capabilities of tput.
$ echo `tput smul`Guide`tput rmul`
Guide
v) uname
Sometimes it is required to quickly determine details like kernel name, version, hostname, etc
of the UBUNTU (UNIX) box you are using.
uname [OPTION]...
uname without any option
When the ‘uname’ command is run without any option then it prints just the kernel name. So
the output below shows that its the ‘Linux’ kernel that is used by this system.
$ uname
Linux
$ uname -s
Linux
5
21CSL35A LINX SYSTEM PROGRAMMING LAB
$ uname -a
Prints all the information
$ uname –n
nhce-desktop
prints the network node hostname
$ uname –r
4.4.0-31-generic
prints the kernel release
$ uname –o
GNU/Linux
prints the operating system
vi) date
Date command is helpful to display date in several formats. It also allows you to set systems
date and time.
When you execute date command without any option, it will display the current date and time
as shown below.
$ date
Wed Nov 2 16:02:24 IST 2022
6
21CSL35A LINX SYSTEM PROGRAMMING LAB
It is both a calculator and a little language for writing numerical programs. Uses the concept of
infix expressions. Once you type bc at the prompt, you are in the calculator more and the $
prompt disappears. That is the only way the reserved and laconic UNIX indicates to you that it
has braced itself to carry out even the most mind boggling calculations.
Ex : bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software
Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
5/2
2
2/2*3
3
1.2*2.5
3.0
scale=4 after decimal 4 values
1.2*2.5
3.00
(143*86)/3
4099.3333 after decimal 4 values
a=100
++a add and assign to a
101
a=100
a++
100 assign and add
obase=2 decimal to binary conversion
10
1010
16
7
21CSL35A LINX SYSTEM PROGRAMMING LAB
10000
15
1111
obase=8 decimal to octal conversion
9
11
16
20
ibase=2 binary to octal conversion..1010 is 10 in decimal and 12 in octal
1010
12
111
7
1000 1000 in binary is equivalent to 8 in decimal which is 10 in octal
10
ibase=2;obase=8 binary to octal conversion
10
2
1000
10
1111 1111 is converted to 15 in decimal and 17 in octal
17
Quit press quit to come out of calculator
$w
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
nhce :0 :0 11:38 ?xdm? 25.66s 0.11s init --user
nhce pts/0 :0 11:41 1.00s 0.12s 0.00s w
$cal –m Jan
Displays the calendar of the month mentioned of the current year
$cal –m Jan 18
Displays the calendar of the month mentioned of the year 2018
$cal 2019
Displays the calendar of the complete year 2019
$cal –3
Displays the previous, current and next month surrounding today
8
21CSL35A LINX SYSTEM PROGRAMMING LAB
$ncal –M
Week starts on Monday
$ncal –S
Week starts on Sunday
$ncal –e
Display date of easter
xiii) calendar
Calendar includes standard holidays and famous birthdays.
$calendar
9
21CSL35A LINX SYSTEM PROGRAMMING LAB
i) head:
Displays first ‘n’ lines of the file.
$head –n <filename>
Or
$cat <filename>| head –n
By default head without specifying n lines displays first 10 lines of the file.
ii) tail:
Displays last ‘n’ lines of the file
$tail –n <filename>
Or
$cat <filename>| tail –n
By default head without specifying n lines displays last 10 lines of the file.
10
21CSL35A LINX SYSTEM PROGRAMMING LAB
iii) cut:
Slicing a file vertically
iv) paste:
This command allows to paste vertically. To concatenate data from files vertically.
–d option is used to specify the delimiter.
$paste –d: <filename>
By default, paste command uses tab as a delimiter.
v) sort:
To sort a file on any possible field(s)
$sort [options] <filename>
Options: -u → removes duplicate lines
-n → numeric sort.
-r → reverse sort.
By default sorting is done on first field in ascending order. If you wish to change the order you
can use the –r option.
vi) tr:
This command manipulates individual characters in a character stream.
$tr options expression1 expression2
It translates each character entered by standard input in expression1 to its mapped counterpart
in expression2.
$tr options expression1 expression2<filename
vii) grep :
This command stands for globally find regular expression and print
$grep<pattern><filename>
Options:
-v: print all lines that do not match a pattern
-i: ignores case
11
21CSL35A LINX SYSTEM PROGRAMMING LAB
In this case jai is treated as pattern whereas sharma and emp is treated as filenames.
If the pattern is jai sharma then use either single/double quotes to show the pattern
$ grep 'jai sharma' emp<enter>
-c: counts the occurences of a pattern.
Ex : You want to list all directory files of your current working directory.
viii) tee
The 'tee' command is a filter program that works like a 'T' connection fitted to a pipeline. It
transfers data unchanged from its standard input to its standard output, but creates a copy of
this data into one or more files that you specify on command line.
If the file does not exist, it is created. If it already exists, it is overwritten. If you want to avoid
this, make use of -a option.
Using tee, you can create a file also
$ tee text1
Now, whatever you type until you press 'ctrl d', will be entered onto file text1. A copy of what
you type is being saved on a disk as a file, while standard output copy appears on your terminal.
ix) wc:
This command counts lines, words and characters depending on the options used.
wc displays a 4 columnar output when it is executed of lines, words, characters and filename.
$wc filename
Options
-l→ counts only number of lines
-w→ counts only number of words
-c→ counts only number of charcters
x) cmp:
12
21CSL35A LINX SYSTEM PROGRAMMING LAB
Compares 2 files
$cmp file1 file2
The 2 files are compared byte by byte and the location of the first mismatch is echoed to the
screen.
xi) diff:
This command gives output of which lines in one file have to be changed to make 2 files
identical.
$diff file1 file2
xii) comm:
This requires 2 sorted files and lists the differing entries in different columns.
$comm file1 file2
The output is a 3 columnar output.
1st column contains lines unique to 1st file
2nd column shows lines unique to the second file
3rd column displays lines common to both files.
xiii) uniq:
This command fetches one copy of each line and writes to standard output.
$uniq file
xiv) nl:
This command numbers all logical lines (lines having something other than newline character)
$nl file
$cat filename
cat is short form of concatenate, which means to join together. This utility is used most often
to display contents of single file. You may also use the cat command to display the contents
of several files in succession. In that case files should be separated by a blank space.
13
21CSL35A LINX SYSTEM PROGRAMMING LAB
$ cat test
Hai this is introduction to unix session.
We will explore our self to a large extent.
$mkdir ABC
mkdir: Cannot create directory ABC : File exists
You may also use the mkdir command to create several directories in succession.
$mkdir XYZ XYZ/a XYZ/b
Creates a directory XYZ and subdirectories a and b under XYZ
You know that everything is treated as files in UNIX, hence ls will list all type of files. It is
difficult to make out which is ordinary file, which is device file etc. For which ls supports an
option called as –l which lists the files in long format. We call it as long listing of files.
14
21CSL35A LINX SYSTEM PROGRAMMING LAB
2) The second column indicates the number of links associated with the file. This is
actually number of filenames maintained by the system of that file.
3) The third column shows the owner of this file.
4) The fourth column stands for group owner.
5) The fifth column shows the size of the file in bytes.
6) The sixth, seventh and eighth column indicates the last modification time of the file,
which is stored to the nearest second.
7) The last column indicates the file name.
UNIX allows the user to change the default permissions that are assigned. The pre condition
however is that you must be the owner of the file. Unless and until you own the file, you cannot
change the permissions assigned to the file.
This command is the key to UNIX permission modes, which provides a simple yet effective
method for controlling access to files. Whenever a file is created, system assigns its default
access permissions to the file. The owner can change these permissions with help of chmod
command.
15
21CSL35A LINX SYSTEM PROGRAMMING LAB
mode: r → read
w → write
x → execute
$ ls -l filename
$ ls -l filename
Note: Modification time has not been changed. This is because changing the access
permissions does not modify the contents of file. The modification time is changed only if the
file’s contents are modified by write operation.
One more format is there called as absolute format – which is based on octal numbers (digits
0 through 7)
All octal values for read, write and execute modes are as follows:
Read → 4
Write → 2
Execute→ 1
In order to express the ways in which you want a particular file to be accessed, simply add the
octal values that correspond to individual types of permissions. (i.e. read, write, execute)
No access = 0
Read access only = 4
Read and execute access = 4 + 1 = 5
Read and write access = 4 + 2 = 6
Read and write and execute access = 4 + 2 + 1 = 7
16
21CSL35A LINX SYSTEM PROGRAMMING LAB
Finally, the added octal rules are expressed in groups of three octal numbers which in turn
indicate desired access modes for file owner, group owner and other user categories.
$ ls -l filename
-rw-rw-rw- 1 nhce root 62 Jul 9 9:35 filename
$ ls -l filename
-rw------- 1 nhce root 62 Jul 9 9:35 filename
xi) umask
New files and directories are created with default set of permissions. For directories, the base
permissions are (rwxrwxrwx) 0777 and for files they are 0666 (rw-rw-rw).
Kernel applies a restriction on the default permission on files & directories by applying a
permission mask called the umask. This is an octal number which has to be subtracted from
default permission.
$umask
0002
The default umask 0002 used for normal user. With this mask default directory permissions
are 0775 and default file permissions are 0664.
The touch command is used to change the timestamps (i.e., dates and times of the most recent
access and modification) on existing files and directories.
When used without any options, touch creates new files for any file names that are provided
as arguments (i.e., input data) if files with such names do not already exist. Touch can create
any number of files simultaneously.
For example, the -a option changes only the access time, while the -m option changes only the
modification time. The use of both of these options together changes both the access and
modification times to the current time
xiii) df
This command gives disk space usage details
xiv) gzip & gunzip
gzip is used to compress the file with .gz as extension
gunzip used to uncompress the .gz file
xv) zip &unzip
17
21CSL35A LINX SYSTEM PROGRAMMING LAB
zip is used to compress the file with .z extension and unzip is used to decompress the .z files
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
18
21CSL35A LINX SYSTEM PROGRAMMING LAB
if( argc==4)
{
if((symlink(argv[2], argv[3]))==-1)
printf(“Cannot create symbolic links\n”);
else
printf(“ Symbolic links created\n”);
}
else
{
if((link(argv[1], argv[2]))==-1)
printf(“Cannot create hard links\n”);
else
printf(“ Hard links created\n”);
}
return 0;
}
OUTPUT:
Create s1.txt,s2.txt.s3.txt and s4.txt with some content
$cc linkprogram.c
$./a.out s1.txt s2.txt s3.txt s4.txt
The Usage of the command is ./a.out –s <original file> <new link>
$./a.out s1.txt
The Usage of the command is ./a.out –s <original file> <new link>
$./a.out –s s1.txt
The Usage of the command is ./a.out –s <original file> <new link>
19
21CSL35A LINX SYSTEM PROGRAMMING LAB
Program #5 Write a program to read the alternate nth byte and write it in another file
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with
the help of “lseek”.
lseek (C System Call): lseek is a system call that is used to change the location of the
read/write pointer of a file descriptor. The location can be set either in absolute or relative
terms.
Function Definition
off_t lseek(int fildes, off_t offset, int whence);
Field Description
int fildes : The file descriptor of the pointer that is going to be moved
off_t offset : The offset of the pointer (measured in bytes).
20
21CSL35A LINX SYSTEM PROGRAMMING LAB
int count = 0;
while (read(f_write, arr, 1))
{
// to write the 1st byte of the input file in
// the output file
if (count < n)
{
// SEEK_CUR specifies that
// the offset provided is relative to the
// current file position
lseek (f_write, n, SEEK_CUR);
21
21CSL35A LINX SYSTEM PROGRAMMING LAB
22
21CSL35A LINX SYSTEM PROGRAMMING LAB
Program #6: Write a program that creates a zombie and then calls system to execute the
ps command to verify that the process is zombie.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pid;
pid=fork(); //Create a child process
if(pid<0)
{
printf("Fork error\n");
exit(0);
}
else if(pid==0)
exit(0); //This is the child process. Exit immediately
23
21CSL35A LINX SYSTEM PROGRAMMING LAB
OUTPUT:
$cc zombie.c
$./a.out
PID PPID S TT COMMAND
9578 9554 S pts/9 bash
13135 9578 S pts/9 ./a.out
13136 13135 Z pts/9 [a.out] <defunt>
13137 13135 S pts/9 sh –c ps –o pid, ppid,state,tty,command
13138 13137 R pts/9 ps -o pid,ppid,state,tty,command
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>
if(pid==0)
execl("/bin/bash","bash","-c",cmdstr,NULL);
else
waitpid(pid,NULL,0);
}
24
21CSL35A LINX SYSTEM PROGRAMMING LAB
OUTPUT:
$cc system.c
$./a.out who date
nhce :0 2022-07-10 15:13(:0)
nhce pts/9 2022-07-11 08:08(:0)
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
int fd;
char buf[1024];
char * myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666); /* create the FIFO (named pipe) */
printf("Writer Process started:\n Run Reader process to read the FIFO File\n");
fd = open(myfifo, O_WRONLY);
write(fd,"USP-CSE", sizeof("Hi")); /* write "USP-CSE" to the FIFO */
close(fd);
25
21CSL35A LINX SYSTEM PROGRAMMING LAB
/* Reader Process */
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#define MAX_BUF 1024
int main()
{
int fd;
char *myfifo = "/tmp/myfifo"; /* A temp FIFO file is not created in reader */
char buf[MAX_BUF];
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Writer: %s\n", buf);
close(fd);
return 0;
}
OUTPUT:
Open 1st Terminal
Run the Writer process first
$cc writer.c
$./a.out
Writer Process Started:
Run reader process to read the FIFO file
26
21CSL35A LINX SYSTEM PROGRAMMING LAB
Program #9a: Write a shell script to accept a file and check if it is executable. If not make
it executable
fi
OUTPUT 1
$ ls –l test.txt
-rwx-r----- 1 nhce cse 345 Jul 18 2019 test.txt
$ sh 9a.sh
27
21CSL35A LINX SYSTEM PROGRAMMING LAB
OUTPUT 2
Program #9b: Write a shell script which will accept a filename and starting and ending
line numbers and displays these lines from given file.
clear
echo “ Enter the filename : “
read fname
echo “ Enter the starting line number : “
read stnum
echo “ Enter the ending line number : “
read endnum
total_lines=` expr $endnum - $stnum + 1 `
echo “ Lines $stnum to $endnum of file $fname is as follows : “
head -$endnum $fname | tail -$total_lines
OUTPUT 1
$ cat test
I come with no wrapping or pretty pink bows.
I am who I am from my head to my toes.
28
21CSL35A LINX SYSTEM PROGRAMMING LAB
OUTPUT 2
$ sh 9b.sh
Enter the filename : test
Enter the starting line number : 6
Enter the ending line number : 9
Lines 6 to 9 of file test is as follows :
You can be you and I can be me.
I try to stay strong when pain knocks me down.
And the times that I cry is when no ones around.
To error is human or so that's what they say.
Program #10a: Write a shell script which displays a list of all the files in the current
directory to which you have read, write and execute permissions.
clear
count=0
echo –n “ Name of all files in current directory having all three permissions : “
for i in *
do
if [ -r $i –a –w $i –a –x $i ]
then
echo File : $i
count=` expr $count + 1 `
fi
done
echo “ Total number of such files are $count “
OUTPUT
$ ls –l
-rwxr----- 1 nhce cse 345 Jul 18 2022 test
29
21CSL35A LINX SYSTEM PROGRAMMING LAB
$sh 10a.sh
Name of all files in current directory having all three permissions:
File :test
File : test1
Total number of such files are 2
Program #10b: A shell script receives even number of filenames as arguments. Suppose
four files are supplied as arguments then the first file should get copied into second, third
file into fourth and so on. If odd number of filenames is supplied then no copying should
take place and an error message should be displayed.
clear
if [ ` expr $# % 2 ` –ne 0 ]
then
echo Odd number of files are supplied as arguments.
echo No copying will take place
exit
else
i=0
for k in $*
do
i=` expr $i + 1 `
if [ $i –eq 1 ]
then
temp1=$k
fi
if [ $i –eq 2 ]
30
21CSL35A LINX SYSTEM PROGRAMMING LAB
then
temp2=$k
i=0
cp $temp1 $temp2
fi
done
fi
OUTPUT 1
$ sh 10b.sh f1 f2 f3
Odd number of files are supplied as arguments.
No copying will take place
OUTPUT 2
$ sh 10b.sh f1 f2 f3 f4
$ cat f1
I come with no wrapping or pretty pink bows.
I am who I am from my head to my toes.
$ cat f2
I come with no wrapping or pretty pink bows.
I am who I am from my head to my toes.
$ cat f3
Even a little crazy some of the time.
I'm not a size 5 and don't care to be.
$ cat f4
Even a little crazy some of the time.
I'm not a size 5 and don't care to be.
Program #11a: Write a shell script which gets executed the moment the user logs in. It
should display the message, “ Good Morning”, “ Good Afternoon”, “ Good Evening”,
depending upon the time at which the user logs in.
clear
time=` date “+%H” `
if [ $time –ge 0 –a $time –lt 12 ]
then
echo GOOD MORNING
elif [ $time –ge 12 –a $time –lt 16 ]
then
echo GOOD AFTERNOON
elif [ $time –ge 16 –a $time –lt 21 ]
then
echo GOOD EVENING
else
echo GOOD NIGHT
fi
OUTPUT
$ sh 11a.sh
31
21CSL35A LINX SYSTEM PROGRAMMING LAB
GOOD MORNING
Program #11b:Write a shell script which accepts any number of arguments and prints
them in reverse order. Ex: If file name is test then $sh test A B C should produce C B A.
clear
for i in $*
do
x=$i” “$x
done
echo $x
OUTPUT1
$ sh 11b.sh A B C
C B A
OUTPUT2
$ sh 11b.sh amar akbar anthony
32
21CSL35A LINX SYSTEM PROGRAMMING LAB
RS: Record Separator FS: Field Separator OFS: Output Field Separator
NR: Number of current records being parsed NF: Number of fields in current record
clear
awk –F”:” ‘
END { print “ Record separator is “,RS }’ EMP
clear
awk –F”:” ‘
END { print “Field separator is “,FS }’ EMP
clear
awk –F”:” ‘
END { print “ Total number of records is “,NR }’ EMP
33
21CSL35A LINX SYSTEM PROGRAMMING LAB
clear
awk –F”:” ‘ BEGIN { print “ Details of Record & Fields” }
{ print “ Record # “,NR,” is having “,NF,” fields }’ EMP
clear
awk –F”:” ‘
END { print “ Input filename is “,FILENAME }’ EMP
Truncated value = 5
34
21CSL35A LINX SYSTEM PROGRAMMING LAB
sqrt(1024.000000) = 32.000000
Length = 16
This function returns the substring of string str, starting at index start of length l. If length is
omitted, the suffix of str starting at index start is returned.
$ awk'BEGIN {
str = "Hello, World !!!"
subs = substr(str, 1, 5)
print "Substring = " subs
}'
Substring = Hello
It checks whether subs is a substring of str or not. On success it returns the position where subs
starts otherwise it returns 0. The first character of str is in position 1.
$ awk 'BEGIN {
str = "One Two Three"
subs = "Two"
printf "Substring \"%s\" found at %d location.\n", subs, index(str, subs)
}'
35
21CSL35A LINX SYSTEM PROGRAMMING LAB
Q3 (a) What are some common shells and what are their indicators?
36
21CSL35A LINX SYSTEM PROGRAMMING LAB
Q8 (a) What is the standard convention being followed when naming files in UNIX?
Q8 (b) Why is it that it is not advisable to use root as the default login?
Q10 (a) Write a shell script to get your name and age
Q10 (b) Write a shell script to print the output in reverse order
37