Unix24 Lab Manual
Unix24 Lab Manual
(2024-2025)
Prepared by
DR.SHABEENA SAYED
Assistant Professor
IT
[1]
[2]
PROGRAMOUTCOMES(POs)
Engineeringstudentswillbeableto:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering
specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development ofsolutions: Designsolutions for complex engineeringproblems and designsystemcomponents or
processes that meet the specified needs with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. Conduct investigations ofcomplex problems: Useresearch-based knowledgeand research methods including design of
experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools
including prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Applyreasoning informedbythecontextual knowledgetoassess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering
practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and with
society at large, such as, being able to comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long
learning in the broadest context of technological change.
PROGRAMSPECIFICOUTCOMES
Studentswillbeableto
13.
PSO1:Organize,maintainandprotectITInfrastructuralresources.
PSO2:DesignandDevelopweb,mobile, andsmartappsbasedsoftwaresolutionstothereal
[3]
CONTENTS
Page
S.No ListofExperiments No
TO STUDY INTRODUCTION OF UNIX AND perform THE
1 INSTALLATION of UNIX.
2 Execution of Unix General Purpose Utility Commands like echo, clear, exit, date, 6
time, uptime, cal, cat, tty, man, which, history, id, pwd, whoami, ping, ifconfig, pr,
lp, lpr, lpstat, lpq, lprm, cancel, mail, etc.
3 A. 12
Study of Unix file system (tree structure), file and directory permissions, single and
multiuser environment
B.
Execution of File System Management Commands like ls, cd, pwd, cat, mkdir,
rmdir, rm, cp, mv, chmod, wc, piping and redirection, grep, tr, echo, sort, head, tail,
diff, comm, less, more, file, type, wc, split, cmp, tar, find, vim, gzip, bzip2, unzip,
locate, etc.
4 Execution of User Management Commands like who, whoami, su, sudo, login, 25
logout, exit, passwd, useradd/adduser, usermod, userdel, groupadd, groupmod,
groupdel, gpasswd, chown, chage, chgrp, chfn, etc
5 ToPracticeonprocess,disk,networkutilities
6 To practice Memory Management Commands in UNIX/Linux with description,
syntax, and examples
7 TopracticeUNIXcommandsonViEditor.
8 a) Study of Shell, Types of Shell, Variables andOperators
b) Execute the following Scripts (at least 6):
(i) Write a shell script to perform arithmetic operations.
(ii) Write a shell script to calculate simple interest.
(iii) Write a shell script to determine largest among three integer numbers.
(iv) Write a shell script to determine a given year is leap year or not
(v) Write a shell script to print multiplication table of given number using
while statement.
(vi) Write a shell script to search whether element is present is in the list or
not.
(vii) Write a shell script to compare two strings.
(viii) Write a shell script to read and check if the directory / file exists or not,
if not make the directory / file.
(ix) Write a shell script to implement menu-driven calculator using case
statement.
(x) Write a shell script to print following pattern
*
**
***
**** [5]
Execute following script using grep/sed command
(i) Write a script using grep command to find the number of words character,
9 words and lines in a file.
(ii) Write ascriptusing egrep command to display list of specific type of files
in the directory.
(iii) Write a script using sed command to replace all occurrences of particular
word in given a file.
(iv) Write a script using sedcommand to print duplicated lines in input.
Assignment 1
11
Assignment2
12
1. TO STUDY INTRODUCTION OF UNIX AND DO THE INSTALLATION.
2. Execution of Unix General Purpose Utility Commands like echo, clear, exit, date, time, uptime, cal, cat, tty, man, which,
history, id, pwd, whoami, ping, ifconfig, pr, lp, lpr, lpstat, lpq, lprm, cancel, mail, etc.
1. echo
Syntax:
Example:
2. clear
Syntax:
clear
Example:
clear
3. exit
Syntax:
exit
Example:
exit
4. date
Syntax:
date [options]
Example:
6
date
5. time
The time command is used to determine how long a command takes to run.
Syntax:
time [command]
Example:
time ls
6. uptime
The uptime command displays how long the system has been running.
Syntax:
uptime
Example:
uptime
7. cal
Syntax:
Example:
cal
cal 12 2025
8. cat
Syntax:
cat [file]
Example:
cat file.txt
7
9. tty
The tty command prints the file name of the terminal connected to standard input.
Syntax:
tty
Example:
tty
10. man
The man command displays the manual pages for other commands.
Syntax:
man [command]
Example:
man ls
11. which
Syntax:
which [command]
Example:
which ls
12. history
Syntax:
history
Example:
history
13. id
The id command prints real and effective user and group IDs.
8
Syntax:
id
Example:
id
14. pwd
Syntax:
pwd
Example:
pwd
15. whoami
Syntax:
whoami
Example:
whoami
16. ping
Syntax:
ping [host]
Example:
ping google.com
17. ifconfig
Syntax:
ifconfig
9
Example:
ifconfig
18. pr
Syntax:
pr [options] [files]
Example:
pr file.txt
Syntax:
lp [options] [files]
Example:
lp file.txt
20. lpstat
Syntax:
lpstat [options]
Example:
lpstat -p
21. lpq
Syntax:
lpq [options]
Example:
lpq
10
22. lprm
The lprm command removes print jobs from the print queue.
Syntax:
Example:
lprm 123
23. cancel
Syntax:
Example:
cancel 123
24. mail
Syntax:
Example:
11
3.
A.Study of Unix file system (tree structure), file and directory permissions, single and multiuser environment
B.
Execution of File System Management Commands like ls, cd, pwd, cat, mkdir, rmdir, rm, cp, mv, chmod, wc,
piping and redirection, grep, tr, echo, sort, head, tail, diff, comm, less, more, file, type, wc, split, cmp, tar, find,
vim, gzip, bzip2, unzip, locate, etc.
.
Aim:To implement file permissions
Description:
1. Unix File System (Tree Structure)
Unix-like operating systems (such as Linux) organize files and directories in a hierarchical tree structure. This structure
starts from the root directory (/) and branches out into subdirectories and files. Here’s a breakdown:
Root Directory (/): At the top of the hierarchy, everything starts from here.
Subdirectories: Directories within directories, forming branches of the tree.
Files: Actual data or programs stored within directories.
12
NAME DESCRIPTION
/ The slash / character alone denotes the root of the filesystem tree.
Unix file
system:
Stands for “binaries” and contains certain fundamental utilities, such
/bin
as ls or cp, which are generally needed by all users.
Contains all the files that are required for successful booting
/boot
process.
Stands for “mount”. Contains file system mount points. These are
used, for example, if the system uses multiple hard disks or hard
/mnt
disk partitions. It is also often used for remote (network) file
systems, CD-ROM/DVD drives, and so on.
The home directory for the super user “root” – that is, the system
administrator. This account’s home directory is usually on the initial
file system, and hence not in /home (which may be a mount point for
another filesystem) in case specific maintenance
/root needs to be performed, during which other filesystems are not
available. Such a
case could occur, for example, if a hard disk drive suffers physical
failures and cannot be
properly mounted.
A place for temporary files. Many systems clear this directory upon
startup; it might
/tmp have tmpfs mounted atop it, in which case its contents do not
survive a reboot, or it
might be explicitly cleared by a startup script at boot time.
The image provides a classification of the Unix file system, listing the different types of files and components in the Unix
operating system. Here's an explanation of each category:
1. Ordinary Files:
2. Directories:
Directories are special files that contain information about other files and subdirectories.
They are used to organize the file system in a hierarchical structure.
Commands like ls and cd are used to interact with directories.
3. Special Files:
Special files are used to represent hardware devices and provide an interface to them.
These include:
o Character Device Files: Used for devices that transfer data character by character (e.g., keyboards, serial ports).
o Block Device Files: Used for devices that transfer data in blocks (e.g., hard drives, USB storage).
4. Pipes:
14
5. Sockets:
Sockets provide an interface for network communication between processes, either on the same machine or across different
machines.
They enable communication using protocols like TCP/IP.
Example: Web servers and clients use sockets for communication.
6. Symbolic Links:
Summary:
The Unix file system is versatile and supports different file types to handle diverse operations. Each type of file serves a
specific purpose, contributing to Unix's ability to manage data, devices, and processes efficiently.
FilePermissions:
Every file and directory in yourUNIX systemhasfollowing3permissionsdefinedfortheuser, groupandothers.
'chmod'commandwhichstands for 'changemode'can set permissions (read, write, execute) ona file/directoryfor the
owner, group and the world.
1. Absolutemode
2. Symbolicmode
Absolute(Numeric)Mode
Inthismode,filepermissionsarenotrepresentedascharactersbutathree-digitoctalnumber.
15
Output:
16
:
Symbolic Mode In the Absolute mode, you change permissions for all 3 owners. In the symbolic mode, you can modify
permissions of a specific owner. It makes use of mathematical symbols to modify the file permissions.
Operator Description
+ Addsapermissiontoa fileordirectory
- Removesthepermission
= Setsthepermissionandoverridesthe
permissions set earlier.
Thevariousownersarerepresentedas-
UserDenotations
u user/owner
g group
o other
a all
Output:
$ ls -l
-rw-r--r-- 1 user group 321 Jan 14 10:00 file.txt
The first column (-rw-r--r--) shows permissions for owner, group, and others respectively.
In a single-user environment, commands are generally used for system maintenance, configuration, or operations that
don't require multi-user interactions. Here is a list of essential Unix commands for a single-user environment:
$ pwd
$ ls
$ cd /path/to/directory
$ mkdir new_folder
$ rmdir empty_folder
$ rm file.txt
$ rm -r folder_to_delete
$ cp source_file destination_file
$ cp -r source_directory destination_directory
$ mv old_name new_name
File Operations
$ cat file.txt
18
more and less - View files one screen at a time.
$ more file.txt
$ less file.txt
$ nano file.txt
$ vim file.txt
$ touch newfile.txt
$ locate filename
$ whoami
$ id
$ ps
$ top
19
Disk Usage and Storage
$ df -h
$ du -h file.txt
System Management
$ date
$ shutdown now
$ reboot
$ gzip file.txt
$ gunzip file.txt.gz
Networking
$ ping example.com
$ curl https://example.com
Miscellaneous
$ man ls
20
$ echo "Hello, Unix!"
These commands are ideal for a single-user working on a Unix system for personal use, development, or system
administration.
Multiuser Environment:
In a multi-user environment, Unix-like systems provide several commands to manage users, groups, permissions, and
system resources effectively. Here's a categorized list of essential commands for managing a multi-user environment:
who
whoami
id
passwd username
21
2. Group Management Commands
groups username
umask 022
ls -l /path/to/directory
ps aux
top
kill 1234
22
nice / renice: Set or modify process priority.
nice -n 10 command
renice 5 -p 1234
uptime
df -h
du -sh /path/to/directory
free -h
6. Networking Commands
netstat -tuln
ping google.com
ssh user@remote_host
last
23
tail -f /var/log/syslog
sudo command
Summary
Understanding Unix file systems, permissions, and environments is crucial for effective system administration and
usage. By grasping these concepts, you can navigate and manage Unix-based systems proficiently, whether in single-
user or multiuser setups. Practice using commands like ls, chmod, and exploring the file tree (/) to reinforce your
understanding.
24
4.Execution of User Management Commands like who, whoami, su, sudo, login, logout, exit, passwd,
useradd/adduser, usermod, userdel, groupadd, groupmod, groupdel, gpasswd, chown, chage, chgrp, chfn, etc
Description:
1. who
who
Output:
2. whoami
whoami
Output:
user1
3. su
su admin
After entering the password, the shell switches to the admin user.
25
4. sudo
5. login
login user1
Prompts for the user's password and logs into the account.
6. logout
logout
7. exit
exit
8. passwd
9. useradd/adduser
Example:
10. usermod
11. userdel
userdel -r username
27
12. groupadd
groupadd developers
13. groupmod
14. groupdel
groupdel developers
15. gpasswd
gpasswd developers
16. chown
Sets user1 as the owner and developers as the group for file.txt.
17. chage
chage -l username
18. chgrp
19. chfn
chfn username
Prompts the user to update personal details like full name and phone number.
Notes:
29
5.To Practice on process,disk,networkutilities
Process utilities:
An instance of a program is calleda Process. In simple terms, any command that you give to your unix machine
starts a new process.
ps:
ps(Processstatus) canbeusedtosee/listalltherunningprocesses.
For more information-f(full) canbe usedalongwith ps
For a singleprocess information,ps along with process id is used
kill:
Wheninvokedkillcommand sends a termination signal to theprocess being killed. Wecanemploysurekill signal to
forcibly terminate a process. Signal number for sure kill is 9
$kill Pid:
30
DiskUtilities:
du:(Diskusuage)
du command-lineutilityhelpsyoutofindoutthediskusageofset offilesoradirectory.
Syntax:du[OPTION]...[FILE]…
31
df:(Diskfreespace)
dfcommand displaystheamountofdiskspaceavailableonthefilesystemcontainingeachfilenameargument.
Syntax:df[OPTION]...[FILE]...
NetworkUtilities:
1. ifconfig:Itisusedtoconfigurenetworkinterfaceparameters.
2. w:
32
wprintsa summaryofthecurrentactivityonthesystem, includingwhateachuserisdoing, andtheirprocesses.
33
34
5.
6. TO PRACTICE Memory Management Commands in UNIX/Linux with description, syntax, and examples.
1. free
Description: Displays the total, used, and available memory (RAM and swap) on the system.
Syntax: free [options]
Example:
free -h
2. /proc/meminfo
Description: A file that provides detailed information about memory usage from the system's perspective.
Syntax: cat /proc/meminfo
Example:
cat /proc/meminfo
Output: Displays details like total memory, free memory, buffers, cached memory, etc.
3. top
Description: Provides a dynamic real-time view of system processes, including memory and CPU usage.
Syntax: top
Example:
top
4. htop
htop
35
Use arrow keys to navigate and F keys for actions (e.g., killing a process).
5. df
df -h
Output: Displays disk space usage in a human-readable format for all mounted filesystems.
6. du
du -sh /var/log
7. vmstat
vmstat 2 5
8. dmidecode
Description: Displays detailed hardware information, including memory details, by decoding the DMI table.
Syntax: dmidecode [options]
Example:
36
9. sar
Description: Collects, reports, and saves system activity, including memory usage.
Syntax: sar [options]
Example:
sar -r 2 5
10. pagesize
pagesize
Output: Returns the memory page size, typically 4096 bytes on most systems.
37
Tips for Memory Management
38
7.TopracticeUNIXcommandsonViEditor.
Vi Editor:The default editor that comes with the UNIX operating system is called vi (visual editor). Using vi editor,
wecan edit an existing file or createa new file. Wecan also use this editor to just read a text file.
Syntax:vifilename
$vipraneetha1
ToworkonVIeditor,youneedtounderstand itsoperationmodes.Theycanbedividedintotwomainparts.
1. Commandmode:
Thevieditor opensinthismode,anditonlyunderstands commands
2. Insertmode:
Thismodeisfor insertingtextinthefile.
ToreturntothecommandmodeandsavethechangesyouhavemadeyouneedtopresstheEsckey
39
viEditingcommands:
ToExitvi:
InsertingorAddingText:
Inserttextbeforecursor, until<Esc>hit
inserttextatbeginningofcurrentline, until <Esc>hit
appendtextaftercursor,until<Esc>hit
appendtextto endofcurrent line,until<Esc>hit
openandputtextinanewlinebelowcurrentline,until<Esc>hit
openandputtextinanewline above currentline,until<Esc>hit
ChangingText:
replacesinglecharacterundercursor(no<Esc>needed)
replacecharacters, startingwithcurrentcursorposition, until <Esc>hit
changethecurrentwordwithnewtext,
cw
startingwiththecharacterundercursor, until<Esc>hit
change(replace) thecharactersinthecurrentline,until<Esc>hit
cc change(replace)theentirecurrentline, stoppingwhen<Esc>ishit
DeletingText:
deletesinglecharacterunder cursor
40
dw deletethesinglewordbeginningwithcharacterundercursor
D deletetheremainderoftheline,startingwithcurrentcursorposition
dd irecurrentline
Output:
Practiceremainingcommandsinexperiment1onvieditor
41
6.
6
6.
8.
a) Study of Shell, Types of Shell, Variables andOperators
b) Execute the following Scripts (at least 6):
(i) Write a shell script to perform arithmetic operations.
(ii) Write a shell script to calculate simple interest.
(iii) Write a shell script to determine largest among three integer numbers.
(iv) Write a shell script to determine a given year is leap year or not
(v) Write a shell script to print multiplication table of given number using while statement.
(vi) Write a shell script to search whether element is present is in the list or not.
(vii) Write a shell script to compare two strings.
(viii) Write a shell script to read and check if the directory / file exists or not, if not make the directory / file.
(ix) Write a shell script to implement menu-driven calculator using case statement.
(x) Write a shell script to print following pattern:
*
**
***
****
(xi) Write a shell script to perform operations on directory like: display name of current directory; display list of directory
contents; create another directory, write contents on that and copy it to a suitable location in your home directory; etc.
7. Execute the following scripts using grep / sed commands:
(i) Write a script using grep command to find the number of words character, words and lines in a file.
(ii) Write ascriptusing egrep command to display list of specific type of files in the directory.
(iii) Write a script using sed command to replace all occurrences of particular word in given a file.
(iv) Write a script using sedcommand to print duplicated lines in input.
8.
Execute the following scripts using awk / perl languages:
(i) Write an awk script to print all even numbers in a given range.
(ii) Write an awk script to develop a Fibonacci series (take user input for number of terms).
(iii) Write a perl script to sort elements of an array.
(iv) Write a perl script to check a number is prime or no
Aim:Toprintthefactorialoffirstnnaturalnumbers.
Program:
echo"enterrange"
read n
i=1
while[$i-le$n] do
j=1 fact=1
while[$j-le$i] do
fact=`expr$fact\*$j` j=`expr
$j + 1`
done
echo factorialof$iis:$fact
42
i=`expr $i + 1`
done
Output:
43
2. Writeashellscriptto generateamultiplicationtableofthegivennumber.
Aim:To generate a multiplication table of the given number.
Description:
To display any information on the screen we can use ‘echo‘ command . The text within the double quoteswas
displayed on the screen. ‘expr’ command is used to evaluate the expression. The expression within the symbol
‘ ‘ is evaluated byusing the expr command $variable gives the value ofthe variable it contained expr command
combines two functions perfumes arithmetic operations on integers manipulate strings
Theoperand+,-,*etc..,mustbe enclosedoneither sidebywhite space.
Program:
echo"whichnumbertogeneratemultiplicationtable"
read number
i=1
while[$i-le10] do
echo "$number*$i=`expr$number \*$i`"
i=`expr $i + 1`
done
Output:
44
3. Writeashellscript thatcountsthenumberoflinesandwordspresentinagiven file.
Aim:Tocountsthenumber oflinesandwordspresentinagiven file.
Description:wccommand isusedto displaythenumberofcharacters, words,lines inagivenfile. “|” inputs the
output of file content to wc.
Program:
echoEnterthefilename
read file
w=`cat$file|wc-w`
c=`cat $file | wc -c`
l=`cat $file | wc -l`
echoNumberofcharactersin$fileis$c
echo Number of words in $file is $w
echo Number of lines in $file is $l
45
4. Writeashellscriptthatdisplaysthelistofallfiles inthegivendirectory.
Aim:Todisplaythelistofallfilesinthegiven directory
Program:
echodirectory
read d
forfilein$d
do
if[-d$file]
then
ls$file
fidone
46
5. Write a shell script (small calculator)that adds, subtracts, multiplies and divides the given two integers.
Therearetwodivisionoptions:onereturnsthequotient andtheotherreturnsreminder.Thescriptrequires3
arguments: The operation to be used and two integer numbers. The options are add (-a), subtract (-s),
multiply (-m), quotient (-c) and reminder (-r).
Program:
echo"enterfirstvalue"
read x
echo"EnterSecondValue" read
y
while[${q:-1}-ne0] do
echo "Enter -a for adding"
echo"Enter-sforsubtraction"
echo"Enter-mformultiplication" echo
"Enter -c for Quotient"
echo"Enter-rforreminder"
echo choice
read b
case$bin
-a)p=`expr$x+$y`
echo "Sum = $p"
;;
-s)p=`expr $x - $y`
echo"difference=$p"
;;
-m)p=`expr$x\*$y`
echo "Product = $p"
;;
-c)p=`expr $x/ $y`
echo "quotient=$p"
;;
-r)p=`expr$x%$y`
echo "reminder=$p"
;;
*)echo"none"br
eak
47
;;
esac
done
Output:
48
6. Writeaprogramthattakesoneormore file/directorynamesascommand line input andreportsthefollowing
information on the file: File type, Number of links, Time of last access, Read, Write and Execute
permissions.
Program:
#include<stdio.h>
#include<unistd.h>
#include<dirent.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<time.h>
intmain(intargc,char *argv[])
{
char *at,*mt,*ct;
struct stat buf;
stat(argv[1],&buf);
printf("theinodenois:%ld\n",buf.st_ino);
if(S_ISDIR(buf.st_mode))
printf("it is a directory");
if(S_ISREG(buf.st_mode))
printf("itisregurlarfile\n");
printf("thenooflinksis%ld\n",buf.st_nlink);
at=ctime(&buf.st_atime);
printf("thetimeoflastaccessis%s\n",at);
mt=ctime(&buf.st_mtime);
printf("themodificationtimeis:%s\n",mt);
ct=ctime(&buf.st_ctime);
printf("time of last change is : %s\n",ct);
if((buf.st_mode &S_IRUSR)==S_IRUSR)
printf("user has read permission\n");
if((buf.st_mode &S_IWUSR)==S_IWUSR)
printf("user has write permisssion\n");
if((buf.st_mode &S_IXUSR)==S_IXUSR)
printf("user has execute permission\n");
if((buf.st_mode &S_IRGRP)==S_IRGRP)
printf("group has read permission\n");
if((buf.st_mode &S_IWGRP)==S_IWGRP)
printf("group has write permission\n");
if((buf.st_mode &S_IXGRP)==S_IXGRP)
printf("group has execute permission\n");
if((buf.st_mode &S_IROTH)==S_IROTH)
printf("others has read permission\n");
if((buf.st_mode&S_IWOTH)==S_IWOTH)
printf("others has write permission\n");
if((buf.st_mode &S_IXOTH)==S_IXOTH)
printf("others has execute permisssion\n");
}
49
Output:
50
7. WriteaCprogramthatillustratesusesoftheopendir, readdir, andclosedirAPIs.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
#include<unistd.h>
int main()
{
chard[10];
DIR *e;
structdirent*sd;
printf("enterdirnametoopen:");
scanf("%s",d);
e=opendir(d);
if(e==NULL)
printf("dirdoesnotexist");
else
{
printf("dir exist\n");
while((sd=readdir(e))!=NULL)
{
printf("%s\t",sd->d_name);
}
closedir(e);
}
}
Output:
51
8. WriteaCprogramthatcountsthenumber ofblanksinatextfileusingstandard I/O
Program:
#include <fcntl.h>
#include<sys/stat.h>
#include <stdio.h>
intmain(intargc,char**argv)
{
FILE
*fd1;intn,cou
nt=0; char
buf;
fd1=fopen(argv[1],"r");
while(!feof(fd1))
{
buf=fgetc(fd1);
if(buf=='')
count=count+1;
}
printf("\nTotalBlanks=%d",count);
return (0);
}
Output:
52
9. Implement inC, Unixcommand‘cat’usingsystemcalls.
Program:
#include<fcntl.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>#defi
ne BUFSIZE 1
intmain(intargc,char**argv)
{
int fd1;
int n;
charbuf;
fd1=open(argv[1],O_RDONLY);
printf("displays filecontents\n");
while((n=read(fd1,&buf,1))>0)
{
write(1,&buf,1);
}
return(0);
}
Output:
53
10. WriteaCprogramthatillustratesthecreationofchild processusingfork systemcall.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.
h>
#include<unistd.h>
int main(int argc,char *argv[])
{
printf("iam:%d\n",(int)getpid()); pid_t
pid=fork();
printf("forkreturned:%d\n",(int)pid);
printf("i am:%d\n",(int)getpid()); return
0;
}
output:
54
11. WriteaCprogramthatillustrateshowtoexecutetwocommandsconcurrentlywitha
command pipe.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.
h>int main()
{
int pfd[2],p;
pipe(pfd);
p=fork();
if(p==0)//forchild
{
close(pfd[0]);
close(1);
dup(pfd[1]);
execlp("who","who", (char *)0);
}
else
{
close(pfd[1]);
close(0);
dup(pfd[0]);
execlp("wc","wc",(char *)0);
}
}
output:
55
12. WriteaCprogramtoimplementtheKillfunction.
Program:
#include<signal.h>
#include<stdio.h>
#include<unistd.h>voi
d xyz(int n)
{
printf("hello:%d\n",getpid());
signal(2,xyz);
}
voidpqr(intn)
{
printf("frompqr:%d\n",getpid());
}
int main()
{
signal(2,xyz);
if(fork()==0)
{
signal(2,pqr);
kill(0,2);
}
while(1)
return0;
}
Output:
56
13. WriteaCprogramtoimplementtheraisefunction.
Program:
#include <stdio.h>
#include<stdlib.h>
#include<signal.h>
voidsignal_handler(intsignal)
{
/*Displayamessageindicatingwehavereceivedasignal*/ if
(signal == SIGUSR1)
printf("ReceivedaSIGUSR1 signal\n");
/*Exittheapplication*/
exit(0);
}
intmain(int argc,constchar*argv[])
{
/*Displayamessageindicatingweareregisteringthesignalhandler*/ printf("Registering the
signal handler\n");
/* Register the signal handler */
signal(SIGUSR1,signal_handler);
/*Displayamessageindicatingweareraisingasignal*/
printf("Raising a SIGUSR1 signal\n");
/*RaisetheSIGUSR1signal*/
raise(SIGUSR1);
/*Displayamessageindicatingweareleavingmain*/
printf("Finished main\n");
return0;
}
Output:
57
14. Writea Cprogramthatdisplaysthe realtimeofa dayevery60seconds.
Program:
#include<stdio.h>
#include<sys/time.h>
#include<sys/signal.h>
#include<unistd.h>
/*Declarations*/
void main();
inttimes_up();
voidmain()
{
for (;;)
{
times_up(1);
sleep(60);
}
}
inttimes_up(sig)
int sig;
{
long now;
structtms*ptr;
long time();
char*ctime();
time(&now);
printf("Itisnow%s\n",ctime(&now));
return (sig);
}
Output:
58
AdditionalPrograms:
1. Writeashellscripttodisplayfileswhichhasread,writeandexecutepermissions.
Program:
echo“enterafilename”
readf
forfin`ls`
do
if[-w$f–a-r $f–a–x$f] then
echo$f
fi
done
2. Writeashellscripttodisplaythebiggestnumberingiveninputnumbers.
Program:
echo“enteranum”
readnum
if[$1–ge$2]
then
if[$1–ge$3]
then
echo$1“isbiggestnum”
else
echo$3“isbiggest num”
fi
elif[$2–ge$3] then
echo$2“isbiggernum”
else
echo“Biggest numis“$3
fi
3. Write aC program that illustrates the creation of child process using fork system call. One process finds sumof
even series and other process finds sum of odd series.
Program:
#include <stdio.h>
#include<sys/types.h>
#include <unistd.h>
#include <fcntl.h>
intmain()
{
int i,n,sum=0;
pid_t pid;
system(“clear”);
printf(“Enternvalue:”);
scanf(“%d”,&n)
pid=fork();
if(pid==0)
{
printf(“Fromchildprocess\n”);
for(i=1;i<n;i+=2)
{
printf(“%d\”,i);
59
sum+=i;
}
printf(“Oddsum:%d\n”,sum);
}
else
{
printf(“Fromprocess\n”);
for(i=0;i<n;i+=2)
{
printf(“%d\”,i);
sum+=i;
}
printf(“Evensum:%d\n”,sum);
}
}
60