0% found this document useful (0 votes)
48 views37 pages

LSP Lab Manual 21CSL35A - Students

The document discusses the Linux system programming lab rubrics and guidelines. It outlines the breakdown of internal assessment marks into continuous assessment and internal tests. It also provides details on the evaluation criteria for programming assignments, including the descriptors and scores for various attributes like program write-up, execution & results, and viva voce. Finally, it introduces some general purpose Linux commands like passwd, who, uname, tput, and their usage syntax and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views37 pages

LSP Lab Manual 21CSL35A - Students

The document discusses the Linux system programming lab rubrics and guidelines. It outlines the breakdown of internal assessment marks into continuous assessment and internal tests. It also provides details on the evaluation criteria for programming assignments, including the descriptors and scores for various attributes like program write-up, execution & results, and viva voce. Finally, it introduces some general purpose Linux commands like passwd, who, uname, tput, and their usage syntax and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

21CSL35A LINX SYSTEM PROGRAMMING LAB

Department of Computer Science & Engineering


21CSL35A - LINUX SYSTEM PROGRAMMING LAB

LAB RUBRICS

Internal Assessment Marks: 50

Divided into two components:

Continuous Assessment: 10 marks

Internal Test: 40 marks

Continuous Assessment:

i) Will be carried out in every lab (for 12 labs -12 programs)


ii) Each lab / program will be evaluated for 10 marks
iii) Totally for 12 lab programs it will be 120 marks. This will be scaled down to 10.

Break up of 10 marks (in every lab):

Will be carried out in every lab (for 12 lab programs)

Attributes Descriptors Scores


Complete program/command with proper variable
3
naming/options
Complete program without proper variable naming or
2
Program Write- command options
up (3)
Incomplete code /command without options 1

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

Viva Voce (2) Answers correctly 2

1
21CSL35A LINX SYSTEM PROGRAMMING LAB

Answers satisfactorily 1

Do not answer any question 0

Record Submits in time and completed (during subsequent lab) 2


completion and
submission (2) Fails to submit the record in time / incomplete submission 0

During the semester, 2 internal tests will be conducted for 20 + 20 =40 marks.

Break up of 20 marks (for each of the 2 internal tests) :

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

Internal Test-1 + 2 : 20+20 Marks

SN EXPLANATION IA1(MARKS) IA2(MARKS)


01 Write up 5 5
02 Execution and results 10 10
03 Viva Voce 5 5
TOTAL 20 20

Attributes Descriptors Scores


Complete program with proper variable naming /
5
command with options
Complete program without variable naming / command
3-4
Program Write- options
up(5)
Incomplete code / command 1-2

Not written 0

Passes all specified test cases efficiently 10


Execution &
Fails in some test cases 5-9
Results (10)
Incomplete execution 0-4

Answers 100% questions correctly 5

Viva Voce(5) Answers 75% questions correctly 3-4

Answers satisfactorily 1-2

2
21CSL35A LINX SYSTEM PROGRAMMING LAB

Do not answer any question 0

SEE Assessment Marks: 50

Attributes Descriptors Scores


Complete program with proper variable naming /
10
command with options
Complete program without variable naming / command
6 -9
Program Write- options
up(10)
Incomplete code / command 1-5

Not written 0

Passes all specified test cases efficiently 30


Execution &
Fails in some test cases 20
Results (30)
Incomplete execution 10

Answers 100% questions correctly 10

Answers 75% questions correctly 6-9


Viva Voce(10)
Answers satisfactorily 1-4

Do not answer any question 0

Program #1: Execution of various general purpose utility commands

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 following are some of the general purpose utility commands


i) $ passwd

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:

(current) UNIX password:


If it is correct, you will then be asked to enter a new password:

Enter new UNIX password:


...and to enter the same password again, to verify it:

Retype new UNIX password:


If the passwords match, the password will be changed.

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:

nhce pt/4 2022-07-11 12:11 (:0)


iv) tput

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.

$ echo `tput bold`guide`tput sgr0`


guide

Start the underline mode:

$ tput smul

Stop the underline mode:

$ 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.

The basic syntax of the uname command is:

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

Prints the kernel name

$ uname -a
Prints all the information

$ uname –p(processor type) or $ uname –i(hardware platform) or $ uname –m(machine


hardware name)
i686
prints the processor type

$ 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

$date +%A Full weekday name


Wednesday

$date +%d day of month


02

$date +%D date


11/02/22

$date +%m month


11

$date +%M minute


06

$date +%Y Year


2022

6
21CSL35A LINX SYSTEM PROGRAMMING LAB

$date +%y last 2 digits of year


22

$date +%h abbreviated month name


Nov

$date +%H hour


16

$date +%j day of year


306

$date +%B Full month name


November

vii) bc : short for base conversion

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

viii) w: Show who is logged on and what they are doing


Displays information about the users currently on the machine and their processes

$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

ix) cal :Displays a calendar


$cal
Displays the calendar of the current month

$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

x) echo: displays a line of text


$echo Hello
Hello

xi) whatis: display one line manual page descriptions


$whatis <command>

xii) man: prints reference manual


$man <command>

xiii) calendar
Calendar includes standard holidays and famous birthdays.
$calendar

xiv) tty: Knowing your terminal


tty command prints the file name of the terminal connected to the standard input
$tty
/dev/pts/0

xv) stty: Set terminal characteristics


$stty –a displays all terminal characteristics
$stty –echo disables echo
$stty echo enables echo
$stty intr \ ^b Changes the interrupt key to Ctrl b
$stty susp \ ^y Changes the interrupt key to Ctrl y
$stty sane Restores sanity to terminal

xvi) script: Records your session


Makes a typescript of everything printed on your terminal
$script -f
Script started, file is typescript
$cat typescript will display the file
$exit
Script done, file is typescript.
The script ends when the shell exits.

9
21CSL35A LINX SYSTEM PROGRAMMING LAB

Program #2: Execution of various filter commands

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

-c option- Cutting columns


$cut –c1-4 <filename>
This cuts columns 1 to 4 from file.
More than one column specification can be cut. Ranges are permitted and commas can be used
to separate the column chunks.

-f option- Cutting fields


-f option should be used with –d delimiter option.
$cut –d: -f1,3 <filename>
This cuts 1st and 3rd field from the file where fields are delimited by :

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>

Ex: $grep abc text


Will display all the lines which contain the pattern abc from file text.
If two or more files are given in grep to search, it includes name of file before each output.

Options:
-v: print all lines that do not match a pattern
-i: ignores case

$ grep –vi abc text

11
21CSL35A LINX SYSTEM PROGRAMMING LAB

-n: displays line numbers in which pattern is found.

$ grep jai sharma emp

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: $ grep -c 'director' file


file:5

^ : searches for pattern at beginning of line.

Ex : You want to list all directory files of your current working directory.

$ ls –l | grep “^d” < enter >

viii) tee

This command copies standard input to standard output and file.


Named after a tee joint in plumbing.
$tee [option] <filename>
option:- -a -> append to file specified.

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

uniq requires a sorted file as input.


Options
-u→ selects the unique lines (that are not repeated)
-d→selects only one copy of the repeated lines
-c→displays the frequency of occurrence of all lines

xiv) nl:
This command numbers all logical lines (lines having something other than newline character)
$nl file

Program #3: Execution of various file/directory handling commands

i) cat:- concatenate and print a 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.

You can also create a file using cat.


$ cat> test <enter>
Hai this is introduction to unix session.
We will explore our self to a large extent.
<ctrl d>

13
21CSL35A LINX SYSTEM PROGRAMMING LAB

$ cat test
Hai this is introduction to unix session.
We will explore our self to a large extent.

ii) mkdir: Creating a directory


$mkdir ABC
Directory ABC is created

$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

iii) cd: Changes the directory to specified name


$cd ABC
~/ABC$
$cd .. Moves one level, to the parent directory
$cd / Moves to root directory

iv) rmdir: Removes directory


Allows to remove the specified directory provided the directory is empty. The directory to be
removed should not be current working directory.
$rmdir XYZ/a XYZ/b XYZ
Removes the tree directory XYZ

v) ls: - to list the files in directories.


Ex : $ls
abc
text
test.c
test1.C

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.

$ ls –l long listing of all files and directories

-rw-r--r-- 1 root nhce 4096 Jul 11 13:34 test.c


drwxr-xr-x 2 root nhce 29 Jul 11 13:34 abc
-rw-r—r-- 1 root nhce 345 Jul 11 13:34 test1.C

The significance of each field is


1) In the long listing if the starting character is hyphen (-) then it is an ordinary file. If it
is d then it is a directory file. What follows after wards i.e remaining 9 characters tells
the permission associated with the file. You have three basic permissions: read(r),
write(w) and execute(x). And these permissions belong to three different type of people:
owner, group and others. We will see this concept little bit later.

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.

$ls –x lists multiple columns


$ls –a lists all hidden files
$ls –lt long listing based on Modification time
$ls –u lists files based on size

vi) pwd: Present working directory

Displays the full path name of the current working directory


$pwd
/root/abc
vii) cp:- copy a file
$cp file1 file2 If target file already exists, it is overwritten.
Contents of file1 are copied onto file2

$cp –r cse ise


Copies all files of cse to ise

viii) mv:- move or rename a file


$mv file1 file2
Moves the contents of file1 to file2 and file1 no longer exists

ix) rm:- remove files or directories


$ rm filename removes file filename

NOTE: To remove more than one file, separate it by a space.


$rm –r XYZ removes recursively all files and directories and XYZ

CAUTION: Do not give $rm *

x) chmod :Change permission mode

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

Syntax: chmod [who] op-code mode <file>

who: → u → file owner


g → group
o → all others
a → all (default)

Opcodes: + → add permission


- → remove permissions

mode: r → read
w → write
x → execute

$ ls -l filename

-rw-rw-rw- 1 nhce root 62 Jul 9 9:35 filename

$ chmod go-rw filename

$ ls -l filename

-rw------- 1 nhce root 62 Jul 9 9:35 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.

This is called symbolic format of accessing the modes.

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.

User Group Others Octal value


r w x r w x r w x
4 2 1 4 2 1 4 2 1 777
4 2 1 4 0 1 0 0 1 751
4 2 0 0 0 0 0 0 0 600

$ ls -l filename
-rw-rw-rw- 1 nhce root 62 Jul 9 9:35 filename

$ chmod 600 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.

xii) touch: change and modify the timestamp

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.

$touch <options> filename

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

Program #4: Write a program to emulate the ln command.

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>

int main( int argc, char *argv[])


{
if(argc<3| | argc>4 | | (argc==3 && (!strcmp(argv[1],”-s”))))
{
printf(“ The Usage of the command is ./a.out –s <original file> <new link>\n”);
return 1;
}

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>

$./a.out s1.txt s2.txt


Hard links created

$./a.out s1.txt s2.txt


Cannot create hard links //Because link is already created in the previous output

$./a.out –s s3.txt s4.txt


Symbolic links created

$./a.out –s s3.txt s4.txt


Cannot create symbolic links //Because link is already created in the previous output

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 whence : The method in which the offset is to be interpreted


(rela, absolute, etc.). Legal value r this variable are provided at the end.
return value : Returns the offset of the pointer (in bytes) from the
beginning of the file. If the return value is -1,
then there was an error moving the pointer.
For example,
say our Input file is as follows:

// C program to read nth byte of a file and


// copy it to another file using lseek
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

void func(char arr[], int n)


{
// Open the file for READ only.
int f_write = open("start.txt", O_RDONLY);

// Open the file for WRITE and READ only.


int f_read = open("end.txt", O_WRONLY);

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

write (f_read, arr, 1);


count = n;
}

// After the nth byte (now taking the alternate


// nth byte)
else
{
count = (2*n);
lseek(f_write, count, SEEK_CUR);
write(f_read, arr, 1);
}
}
close(f_write);
close(f_read);
}
main Driver code
int main()
{
char arr[100];
int n;
n = 5;

// Calling for the function


func(arr, n);
return 0;
}
Output file (end.txt) file (end.txt)

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

sleep(2); //This is the parent process. Sleep for a minute

23
21CSL35A LINX SYSTEM PROGRAMMING LAB

system( "ps -o pid,ppid,state,tty,command");


}

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

Program #7: Write a program to implement the system function.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>

void sys(const char *cmdstr)


{
int pid;
pid=fork();

if(pid==0)
execl("/bin/bash","bash","-c",cmdstr,NULL);
else
waitpid(pid,NULL,0);
}

24
21CSL35A LINX SYSTEM PROGRAMMING LAB

int main(int argc, char *argv[])


{
int i;
for(i=1;i< argc;i++)
{
sys(argv[i]);
printf("\n");
}
exit(0);
}

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)

Thu Jul 11 16:50:56 IST 2022

Program #8: Write a program which demonstrates inter-process communication between


a reader process and a writer process. (Use mk fifo, open, read, write and close APIs)
/*Writer Process*/

#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

unlink(myfifo); /* remove the FIFO */


return 0;
}

/* 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

Open 2nd Terminal


Run the reader process
$cc reader.c
$./a.out
Reader Process Started:
Message from writer USP-CSE

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

echo “Enter the filename : “


read fname
if [ -x $fname ]
then
echo File $fname has executable permission
else
echo File $fname is not having executable permission
chmod 744 $fname
echo It is now made 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

Enter the filename


test.txt
File test.txt has executable permission

OUTPUT 2

$ chmod 600 test.txt


$ ls –l test.txt
-rw------- 1 nhce cse 345 Jul 18 2022 test.txt
$ sh 9a.sh
Enter the filename : test.txt
File test is not having executable permission
It is now made executable
$ ls –l test.txt
-rwxr--r-- 1 nhce cse 345 Jul 18 2022 test.txt

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

I tend to get loud when speaking my mind.


Even a little crazy some of the time.
I'm not a size 5 and don't care to be.
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.
Well tell me who's perfect anyway.
$ sh 9b.sh
Enter the filename :test
Enter the starting line number :2
Enter the ending line number :4
Lines 2 to 4 of file test is as follows :
I am who I am from my head to my toes.
I tend to get loud when speaking my mind.
Even a little crazy some of the time.

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

-rwxr----- 1 nhce cse 134 Jul 18 2022 test1


-rw-r----- 1 nhce cse 45 Jul 18 2022 test2
-rw-r----- 1 nhce cse 345 Jul 18 2022 test3

$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

anthony akbar amar

32
21CSL35A LINX SYSTEM PROGRAMMING LAB

Program #12a: Write scripts to demonstrate built in variables available in AWK

RS: Record Separator FS: Field Separator OFS: Output Field Separator

NR: Number of current records being parsed NF: Number of fields in current record

FILENAME: Current input filename

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

Program #12b: Write scripts to demonstrate built in functions available in AWK

Built-in functions available in AWK:

int(x)→ returns integer value of x


$ awk'BEGIN {
param = 5.12345
result = int(param)
print "Truncated value =", result
}'

On executing the above code, you get the following result:

Truncated value = 5

sqrt(x)→returns square root of x


$ awk'BEGIN {
param = 1024.0
result = sqrt(param)
printf "sqrt(%f) = %f\n", param, result
}'

34
21CSL35A LINX SYSTEM PROGRAMMING LAB

On executing the above code, you get the following result:

sqrt(1024.000000) = 32.000000

length→returns length of complete record


length(x)→returns length of x
$ awk'BEGIN {
str = "Hello, World !!!"
print "Length = ", length(str)
}'

On executing the above code, you get the following result:

Length = 16

substr(s1,s2,s3)→returns portion of string of length s3, starting from position s2 in string s1

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
}'

On executing the above code, you get the following result:

Substring = Hello

index(s1,s2)→ returns position of string s2 in string s1

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)
}'

On executing the above code, you get the following result:

Substring "Two" found at 5 location.


system(“cmd”)→runs any valid unix command
........................................

35
21CSL35A LINX SYSTEM PROGRAMMING LAB

Q. No. Sample Questions

Q1 (a) What is Linux?

Q1 (b) Illustrate the features of Linux

Q2 (a) What is kernel?

Q2 (b) What is shell?

Q3 (a) What are some common shells and what are their indicators?

Q3 (b) Differentiate multiuser from multitask.

Q4 (a) What is touch command

Q4 (b) Differentiate relative path from absolute path.

Q5 (a) Explain the importance of directories in a UNIX system

Q5 (b) Explain the usage of umask

36
21CSL35A LINX SYSTEM PROGRAMMING LAB

Q6 (a) What is the use of chmod command

Q6 (b) What is a superuser?

Q7 (a) How do you determine and set the path in UNIX?

Q7 (b) Is it possible to see information about a process while it is being executed?

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?

Q9 (a) What is the use of the tee command?

Q9 (b) Examine zombie process.

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

You might also like