Linux Programming Lab Manual
Linux Programming Lab Manual
LABORATORY MANUAL&RECORD
B.TECH (R17)
VISION
To improve the quality of technical education that provides efficient software engineers
with an attitude to adapt challenging IT needs of local, national and international arena,
MISSION
Department intends to meet the contemporary challenges in the field of IT and is playing a
vital role in shaping the education of the 21st century by providing unique educational and
research opportunities.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
To facilitate the graduates with the ability to visualize, gather information, articulate, analyze,
solve complex problems, and make decisions. These are essential to address the challenges of complex
and computation intensive problems increasing their productivity.
To facilitate the graduates with the technical skills that prepare them for immediate employment
and pursue certification providing a deeper understanding of the technology in advanced areas of
computer science and related fields, thus encouraging to pursue higher education and research based on
their interest.
To facilitate the graduates with the soft skills that include fulfilling the mission, setting goals,
showing self-confidence by communicating effectively, having a positive attitude, get involved in team-
work, being a leader, managing their career and their life.
To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety codes, and
adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
After the completion of the course, B. Tech Information Technology, the graduates will have the following
Program Specific Outcomes:
1. Fundamentals and critical knowledge of the Computer System:- Able to Understand the working
principles of the computer System and its components , Apply the knowledge to build, asses, and analyze
the software and hardware aspects of it .
3. Applications of Computing Domain & Research: Able to use the professional, managerial,
interdisciplinary skill set, and domain specific tools in development processes, identify the research gaps,
and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time), those who come
after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the synopsis/
program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm, Procedure, Program,
Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted to you by the
faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note book, and get
certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the discipline and
decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should beutilized
properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab sessions. Misuse of
the equipment, misbehaviors with the staff and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody found loitering
outside the lab / class without permission during working hours will be treated seriously and punished
appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after completing
the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.
Step 3 : Ubuntu will start now initialize and after few minutes you can see the installation wizard.
1
Step 4 : Click Forward and it will check manually option. You can choose the 1st option if
the minimum requirements for running ubuntu on you just want linux to exist in your system. Else
your PC. If everything is fine you can see green select second option. Now it will display the free
colored tick marks. You can also select to download space available for your pc.
updates while installing and install some third party
software. After selecting the things you want click
forward.
2
Now again select free space from the table and click
add option. Now select size to be around twice the
size of your ram that is around 1000 mb if your ram
size is 512mb and select use as swap area and click
ok.
3
Step 7 : While you are selecting these options wizard
will continue to copy files. Now select your desired
keyboard layout and click forward.
Step 8 : Now fill in the details about yourself. Fill your name, computer name, choose a username and create a
password and click forward and let ubuntu copy all the essential files.
4
Step 9 : After all files have been copied and installed ubuntu will display a message saying that installation
complete and click on restart button to restart your computer. Remove the cd from the cd drive.
Step 10 : After restarting your pc wait for the ubuntu to load and then it will display the login screen. Choose the
user and enter password and click login.
5
6
A-Z Index of the Bash command line for Linux
a
a
a a
i
iconv Convert the character set of a file
id Print user and group id's
if Conditionally perform a command
ifconfig Configure a network interface
install Copy files and set attributes
ip Routing, devices and tunnels
j
jobs List active jobs •
join Join lines on a common field
k
kill Kill a process by specifying its PID
killall Kill processes by name
l
let Perform arithmetic on shell variables •
link Create a link to a file
ln Create a symbolic link to a file
local Create a function variable •
locate Find files
logname Print current login name
logout Exit a login shell •
look Display lines beginning with a given string
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
ls List information about file(s)
lsof List open files
m
make Recompile a group of programs
man Help manual
mkdir Create new folder(s)
mkfifo Make FIFOs (named pipes)
mkfile Make a file
mktemp Make a temporary file
more Display output one screen at a time
most Browse or page through a text file
9
mount Mount a file system
mtools Manipulate MS-DOS files
mtr Network diagnostics (traceroute/ping)
mv Move or rename files or directories
mmv Mass Move and rename (files)
n
nc Netcat, read and write data across networks
netstat Networking connections/stats
nice Set the priority of a command or job
nl Number lines and write files
nohup Run a command immune to hangups
notify-send Send desktop notifications
nslookup Query Internet name servers interactively
o
open Open a file in its default application
op Operator access
p
passwd Modify a user password
paste Merge lines of files
ping Test a network connection
pgrep List processes by name
pkill Kill processes by name
popd Restore the previous value of the current directory
pr Prepare files for printing
printcap Printer capability database
printenv Print environment variables
printf Format and print data •
ps Process status
pushd Save and then change the current directory
pv Monitor the progress of data through a pipe
pwd Print Working Directory
q
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
r
ram ram disk device
rar Archive files with compression
rcp Copy files between two machines
read Read a line from standard input •
readarray Read from stdin into an array variable •
readonly Mark variables/functions as readonly
reboot Reboot the system
rename Rename files
renice Alter priority of running processes
remsync Synchronize remote files via email
return Exit a shell function
rev Reverse lines of a file
rm Remove files
10
rmdir Remove folder(s)
s
screen Multiplex terminal, run remote shells via ssh
scp Secure copy (remote file copy)
sdiff Merge two files interactively
sed Stream Editor
select Accept keyboard input
seq Print numeric sequences
set Manipulate shell variables and functions
sftp Secure File Transfer Program
shift Shift positional parameters
shopt Shell Options
shutdown Shutdown or restart linux
sleep Delay for a specified time
slocate Find files
sort Sort text files
source Run commands from a file '.'
split Split a file into fixed-size pieces
ss Socket Statistics
ssh Secure Shell client (remote login program)
su Substitute user identity
sudo Execute a command as another user
sum Print a checksum for a file
suspend Suspend execution of this shell •
t
tail Output the last part of file
tar Store, list or extract files in an archive
tee Redirect output to multiple files
test Evaluate a conditional expression
time Measure Program running time
timeout Run a command with a time limit
times User and system times
touch Change file timestamps
top List processes running on the system
tput Set terminal-dependent capabilities, color, position
traceroute Trace Route to Host
trap Execute a command when the shell receives a signal •
tr Translate, squeeze, and/or delete characters
true Do nothing, successfully
tsort Topological sort
tty Print filename of terminal on stdin
type Describe a command •
u
ulimit Limit user resources •
umask Users file creation mask
umount Unmount a device
11
unalias Remove an alias •
uniq Uniquify files
units Convert units from one scale to another
until Execute commands (until error)
uptime Show uptime
useradd Create new user account
userdel Delete a user account
usermod Modify user account
users List users currently logged in
v
v Verbosely list directory contents (`ls -l -b')
vdir Verbosely list directory contents (`ls -l -b')
vi Text Editor
vmstat Report virtual memory statistics
w
w Show who is logged on and what they are doing
wait Wait for a process to complete •
watch Execute/display a program periodically
wc Print byte, word, and line counts
whereis Search the user's $path, man pages and source files
for a program
which Search the user's $path for a program file
while Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
wget Retrieve web pages or files via HTTP, HTTPS or FTP
write Send a message to another user
x
xargs Execute utility, passing constructed argument list(s)
xdg-open Open a file or URL in the user's preferred application.
xz Compress or decompress .xz and .lzma files
yes Print a string until interrupted
zip Package and compress (archive) files.
. Run a command script in the current shell
!! Run the last command again
### Comment / Remark
12
Procedure to connect to LINUX(putty)
Step 1:click on putty icon available on desk top. A window is opened
Step 3: provide login and password (nothing is displayed on screen while typing password)
Step 4:changethe default password at your first login
13
II) Practice the Linux Commands
14
15
Text processing utilities
16
17
Network and Processing utilities
18
19
Backup utilities
20
Disk utilities
21
Filters
22
23
EXPERIMENT NO: 1 Date:
Aim: Write a Shell Script that accepts a file name, starting and ending line numbers
as Arguments and displays all lines between the given line numbers.
ALGORITHM:
Step 1: Create a file with 5-6 lines of data
File can be created by vi sample.dat or cat sample.dat
Step 2:Now write a shell script with
vi 1.sh
step3:Check the no of arguments for shell script
if 0 arguments then print no arguments
else if 1 argument then print 1 argument
else if 2 arguments then print 2 arguments
else check for file is there or not(if file is not there print file does not exists)
1else sed -ne ''$2','$3' p' $1
sed is one of powerful filter(stream editor)
-e default option (script on command line)
-n suppresses automatic output
$2 first line number passed $3 2nd line number passed
p is a print command (prints current content to the pattern space).
$1 is name of file from which we are printing data between the line numbers.
Step 4:top
Sed command:
stream editor for filtering and transforming text
1. Replacing or substituting string
Sed command is mostly used to replace the text in a file. The below simple sed command
replaces the word "unix" with "linux" in the file.
$sed 's/unix/linux/' file.txt
Execution:
Viva Questions
1. What is a shell script?
2. How to find current shell name
3.How to switch to another shell
4.How to execute shell Script
Assignment :-
25
26
27
EXPERIMENT NO: 2 Date:
AIM: Write a shell script that deletes all lines containing the specified word in one or more files
Supplied as arguments to it.
ALGORITHM:
#!/bin/bash
if [ $# -lt 2 ]then
echo "Enter atlest two files as input in command line"
else
printf "enter a word to find:"
read word
for f in $*
do
printf "\n In File $f:\n"
sed /$word/d $f
done
fi
Execution:
run1:
check data in input files
[root@localhost sh]# cat abc1.txt
abc
def
ghi
abc
abc
cccc
[root@localhost sh]# cat abc2.txt
abc
28
def
ghi
abc
abc
cccc
Executing shell script
[root@localhost sh]# sh 2.sh abc1.txt abc2.txt
enter a word to find:abc
In File abc1.txt:
def
ghi
cccc
In File abc2.txt:
def
ghi
cccc
Expected output:
Displays lines from files s1 s2 after deleting the word hi
Viva Questions
Assignment :-
29
EXPERIMENT NO: 3 Date:
Aim: Write a shell script that displays a list of all files in the current directory to which the user
has read, write and execute permissions.
ALGORITHM:
Execution:
$sh 3.sh
Expected output:
by executing above shell script you will get all files which has read ,write and execute
Permissions in current working directory
sample output
[root@localhost sh]# sh 3.sh
List of Files which have Read, Write and Execute Permissions in Current Directory are...
5.sh
a.out
Viva Questions:
1.Display all files in a directory
2.how to use chmod
3.How to change file permissions
Assignment :-
Sno Task Date Sign Remark
1 Write a shell script to display all file with read or write or execute
permissions provide a selection menu
2 Write a comparison report for using chmod using symbolic
representation or octal number representation
3 Write a shell script to count no of file in current directory with full
permissions
30
28
EXPERIMENT NO: 4 Date:
Aim:-Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or directory and reports accordingly. Whenever the
argument is a file it reports no of lines present in it
ALGORITHM:
step 1: if arguments are less than 1 print Enter at least one input file name and goto step 9
Step 2: selects list a file from list of arguments provided in command line
Step 3: check for whether it is directory if yes print is directory and goto step 9
step 4: check for whether it is a regular file if yes goto step 5 else goto step 8
Step 5: print given name is regular file
step 6: print No of lines in file
step 7: goto step
step 8: print not a file or a directory
step 9: stop
Execution:
provide two file names as input one a regular file and other directory
for example abc1.txt a text file as first argument and vazralu a directory as second argument
Run1:
[root@localhost sh]# sh 4.sh abc1.txt vazralu
given name is file: abc1.txt
No of lines in file are : 7 abc1.txt
31
vazralu is directory
Viva Questions:
2. x and y are two variables containing numbers? How to add these 2 numbers?
$ expr $x + $y
4. How to find the list of files modified in the last 30 mins in Linux?
$ find . -mmin -30
Assignment :-
32
EXPERIMENT NO: 5 Date:
Aim:-Write a shell script that accepts a list of file names as its arguments, counts and
reports the occurrence of each word that is present in the first argument file on other
argument files.
ALGORITHM:
Script name:5.sh
#!/bin/bash
echo "no of arguments $#"
if [ $# -le 2 ]
then
echo "Error : Invalid number of arguments."
exit
fi
str=`cat $1 | tr '\n' ' '`
for a in $str
do
echo "in file $a"
echo "Word = $a, Count = `grep -c "$a" $2`"
done
Viva Questions
Assignment :-
Sno Task Date Sign Remark
1 Write a shell script to print prime numbers
2 Write a shell script to print Fibonacci numbers
Viva Questions
1. A string contains a absolute path of a file. How to extract the filename alone from the absolute
path in Linux?
$ x="/home/guru/temp/f1.txt"
$ echo $x | sed 's^.*/^^'
2. How to find all the files created after a pre-defined date time, say after 10th April 10AM?
This can be achieved in 2 steps:
1. Create a dummy file with the time stamp, 10th April 10AM.
2.Find all the files created after this dummy file.
3. The word "Unix" is present in many .txt files which is present across many files and also
files present in sub directories. How to get the total count of the word "Unix" from all the .txt
files?
$ find . -name *.txt -exec grep -c Unix '{}' \; | awk '{x+=$0;}END{print x}'
Assignment :-
36
30
EXPERIMENT NO: 7 Date:
Script Name:7.sh
#!/bin/bash
echo "Factorial Calculation Script. .."
echo "Enter a number: "
read f
fact=1
factorial=1
while [ $fact -le $f ]
do
factorial=`expr $factorial \* $fact`
fact=`expr $fact + 1`
done
echo "Factorial of $f = $factorial"
Assignment :-
37
30
EXPERIMENT NO: 8 Date:
Aim:-write an awk script to count number of lines in a file that does not contain vowels
ALGORITHM
Step 1: create a file with 5-10 lines of data
Step 2: write an awk script by using grep command to filter the lines
that do not contain vowels
awk ‘ $0 ~/aeiou/ {print $0}’ file1
step3: count=count+1
step4:print count
step5:stop
Awk script name:nm.awk
BEGIN{}
{
If($0 !~/[aeiou AEIOU]/)
wordcount+=NF
}
END
{
print "Number of Lines are", wordcount
}
input file for awk script:data.dat
bcdfghj
abcdfghj
bcdfghj
ebcdfghj
bcdfghj
ibcdfghj
bcdfghj
obcdfghj
bcdfghj
ubcdfghj
Executing the script:
[root@localhost awk]# awk -f nm.awk data.dat
bcdfghj
bcdfghj
bcdfghj
bcdfghj
bcdfghj
Number f lines are 5
Assignment :-
Aim:-write an awk script to find the no of characters ,words and lines in a file
ALGORITHM
Step 1: create a file with 5 to10 lines of data
Step 2: write an awk script
find the length of file
store it in chrcnt
step3: count the no of fields (NF), store it in wordcount
step4: count the no of records (NR), store it in NR
step5: print chrcnt,NRwordcount
step6: stop
Awk script name:nc.awk
BEGIN{}
{
print len=length($0),"\t",$0
wordcount+=NF
chrcnt+=len
}
END {
print "total characters",chrcnt
print "Number of Lines are",NR
print "No of Words count:",wordcount
}
VIVA QUESTIONS:
1. How to find the last modified file or the newest file in a directory?
$ ls -lrt | grep ^- | awk 'END{print $NF}'
2. How to access the 10th command line argument in a shell script in Linux?
$1 for 1st argument, $2 for 2nd, etc... For 10th argument, ${10}, for 11th, ${11} and so on.
4. How to delete a file which has some hidden characters in the file name?
Since the rm command may not be able to delete it, the easiest way to delete a file with some hidden
characters in its name is to delete it with the find command using the inode number of the file.
$ ls –li
total 32
9962571 -rw-r--r-- 1 guru users 0 Apr 23 11:35
$ find . -inum 9962571 -exec rm '{}' \;
5. Using the grep command, how can you display or print the entire file contents?
$ grep '.*' file
6. What is the difference between a local variable and environment variable in Linux?
A local variable is the one in which the scope of the variable is only in the shell in which it is defined. An
environment variable has scope in all the shells invoked by the shell in which it is defined.
38
30
EXPERIMENT NO: 10 Date:
SYNTAX:
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
-v Non-printing characters (with the exception of tabs, new-lines & form-feeds) are printed visibly.
3. To display a file:
$cat file1.txt
This command displays the data in the file.
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
int fd,n;
char buff[512];
if(argc!=2)
printf("ENTER CORRECT ARGUMENTS :");
if((fd=open(argv[1],4))<0)
{
printf("ERROR");
return 0;
}
while(n=read(fd,buff,sizeof(buff))>0)
write(1,buff,n);
}
Algorithm:
Step 1. Start.
Step 2. open directory using opendir( ) system call.
Step 3. read the directory using readdir( ) system call.
Step 4. print dp.name and dp.inode .
Step 5. repeat above step until end of directory.
Step 6: Stop.
Algorithm:
Step 1: Start
Step 2: open an existed file and one new open file using open() system call
Step 3: read the contents from existed file using read( ) system call
Step 4:write these contents into new file using write system call using write( ) system call
Step 5: repeat above 2 steps until eof
Step 6: close 2 file using fclose( ) system call
Step 7: delete existed file using using unlink( ) system
Step 8: Stop.
#include<stdio.h>
#include<string.h>
int main(int argc ,char *argv[])
{
int r,i;
char p[20],q[20];
if(argc<3)
printf("improper arguments\n file names required\n");
else
if( argc==3)
{
printf("\n%s\n",argv[1],argv[2]);
r=link(argv[1],argv[2]);
printf("%d\n",r);
unlink(argv[1]); 41
30
}
else
{
for(i=1;i<argc-1;i++)
{
strcpy(p,argv[argc-1]);
strcat(p,"/");
strcat(p,argv[i]);
printf("%s%s\n",argv[i],p);
link(argv[i],p);
unlink(argv[i]);
}
}
}
Expected Output
42
30
EXPERIMENT NO: 11 Date:
Aim:Write a C program that takes one or more file/directory names as
command line input and reports following information
A) File Type B)Number Of Links
c) Time oflast Acces D) Read,write and execute permissions
Algorithm:
Step 1:start
Step 2:Declare struct stat a
Step 3:read arguments at command line
Step 4: set the status of the argument using stat(argv[i],&a);
Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode)
if it is a directory file print Directory file
Else
print is Regular file
Step6: print number of links
Step 7:print last time access
Step 8:Print Read,write and execute permissions
Step 9:stop
Assignment:
Sno Task Date Sign Remark
1 write a c program that simulates mkdir command using system
calls
2 write a c program that simulates rmdir command using system
calls
44
30
EXPERIMENT NO: 12
Aim:Write a C program to list every file in directory, its inode number and file name
Algorithm:
Step 1:Start
Step 2:Read Directory name
Step 3:open the directory
Step 4: print file name and Inode number of each file in the directory
Step 5:Stop
Program file name:inode.c
#include<fcntl.h>
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
int main(int argc,char*argv[])
{
DIR *dirop;
struct dirent *dired;
if(argc!=2)
{
printf("Invalid number of arguments\n");
}
else if((dirop=opendir(argv[1]))==NULL)
45
30
EXPERIMENT NO: 13 Date:
Aim:Write a C program to create child process and allow parent process to display
“parent” and the child to display “child” on the screen
Algorithm:
Step 1: start
Step2: call the fork() function to create a child process
fork function returns 2 values
step 3: which returns 0 to child process
step 4:which returns process id to the parent process
step 5:stop
Execution:
Aim:- Write a C program that illustrate communication between two unrelated process
using named pipes
Step 1:start
Step 2:check whether the no of arguments specified were correct or not
Step 3:if no of arguments are less then print error message
Step 4:Open the first named pipe for writing by open system call by setting
O_WRONLY Fd=open(NP1,O_WRONLY)
Step 5: .Open the second named pipe for reading by open system call by setting
O_RDONLY Fd=open(NP2,O_RDONLY)
Step 6: write the data to the pipe by using write system call
write(fd,argv[1],strlen(argv[1]))
Step 7: read the data from the first pipe by using read system call
numread=Read(fd,buf,MAX_BUF_SIZE) buf*numread+=’\0’
Step 8: print the data that we have read from pipe
Step 9:stop
sleep(10);
write(wfd,fname,2000);
n=read(rfd,buff,2000);
buff[n]='\0';
printf("THE RESULTS OF CLIENTS ARE ...... \n");
write(1,buff,n);
}
void server(int rfd,int wfd)
{
int i,j,n; char fname[2000];
char buff[2000];
50
30
n=read(rfd,fname,2000);
fname[n]='\0';
int fd=open(fname,O_RDONLY);
sleep(10);
if(fd<0)
write(wfd,"can't open",9);
else
n=read(fd,buff,2000);
write(wfd,buff,n);
}
Assignment:
Sno Task Date Sign Remark
1 Write a program to demonstrate the function of a pipe
2 Write a program to demonstrate the pipe function using dup() system call
51
30
EXPERIMENT NO: 17 Date:
Aim:-Write a C program that receives a message from message queue and display them
Algorithm:
Step 1:Start
Step 2:Declare a message queue structure
typedef struct msgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;
Mtype =0 Retrieve the next message on the queue, regardless of its mtype.
PositiveGet the next message with an mtype equal to the specified
msgtyp.
Negative Retrieve the first message on the queue whose mtype field is
less than or equal to the absolute value of the msgtyp argument.
Usually mtype is set to1
mtext is the data this will be added to the queue.
Step 3:Get the message queue id for the "name" 1234, which was created by the server
key = 1234
Step 4 : if ((msqid = msgget(key, 0666< 0) Then print error
The msgget() function shall return the message queue identifier associated with the argument key.
Step 5: Receive message from message queue by using msgrcv function
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
#include < sys/msg.h>
(msgrcv(msqid, &rbuf, MSGSZ, 1, 0)
msqid: message queue id
&sbuf: pointer to user defined structure MSGSZ: message size
Message type: 1
Message flag:The msgflg argument is a bit mask constructed by ORing together zero or
more of the following flags: IPC_NOWAIT or MSG_EXCEPT or MSG_NOERROR
Step 6:if msgrcv <0 return error
Step 7:otherwise print message sent is sbuf.mext
Step 8:stop
Assignment:
Sno Task Date Sign Remark
1 Write a program to demonstrate a single process create a message queue and
sends itself a “welcome “ message via the queue
2 Write a program to demonstrate how we can print the status information
about the queue
52
30
EXPERIMENT NO: 18 Date:
Aim:-Write a C program to allow cooperating process to lock a resource for exclusive
use using, a) Semaphore
#include<stdio.h>
#include<stdlib.h>
#include<error.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
int main(void)
{
key_t key;
int semid;
union semun arg;
if((key==ftok("sem demo.c","j"))== -1)
{
perror("ftok");
exit(1);
}
if(semid=semget(key,1,0666|IPC_CREAT))== -1)
{
perror("semget"):
exit(1);
}
arg.val=1;
if(semctl(semid,0,SETVAL,arg)== -1)
{
perror("smctl");
exit(1);
}
return 0;
}
Assignment:
Sno Task Date Sign Remark
1 Write a program using the simpler semaphore operation
2 Write a program to create a semaphore
53
30
EXPERIMENT NO: 19 Date:
Aim:-Write a C program that illustrate the suspending and resuming process using signal
Algorithm:
Step 1: call the signal function to generate the signal
Step 2:execution of process will be started
Step 3:call alarm function to suspend the execution of current process
Step 4:then it will execute the signal function
Step 5:again the process will be resumed
Step 6:stop
Program
#include<stdio.h>
int main()
{
int n;
if(signal(SIGALRM,sig_alarm)==SIG_ERR)
printf(‚Signal error‛);
alarm(5);
for(n=0;n<=15;n++)
printf(‚from for loop n=%d‛,n);
printf(‚main program terminated‛);
}
Assignment:
Sno Task Date Sign Remark
1 Write a program using kill and rise functions
2 Write a program using abort()
54
30
EXPERIMENT NO: 21 Date:
Aim:-Write a C program that implements producer –consumer system with two processes using
semaphores
Algorithm for producer :
step 1:Start
step 2:Create a named pipe by using mkfifo system call Pipe1=mkfifo(NP1,0666)
step 3:if mkfifo returns -1 then print a message that error in creating the pipe
step 4:Open the pipe for reading by open system call by setting O-RDONLY Fd=open(NP1,O-
RDONLY)
step 5:read the data from the pipe by using read system call
numread=Read(fd,buf,MAX-BUF-SIZE)
step 6:print the data that we have read from pipe
step 7:convert the data to the upper case.
step 8:print the converted data
step 9:stop.
Algorithm for consumer:
Step 1:start
step 2:check whether the no of arguments specified were correct or not
step3:if no of arguments are less then print error message
step 4:Open the pipe for writing by open system call by setting O_WRONLY
Fd= open (NP1, O_WRONLY )
step 5: write the data to the pipe by using write system call write(fd,argv[1],strlen(argv[1]))
step 6:stop
Consumer:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#define MAXSIZE 10
#define FIFO_NAME "myfifo"
int main()
{
int fifoid; int fd, n; char *r;
system("clear");
r=(char *)malloc(sizeof(char)*MAXSIZE); int open_mode=O_RDONLY;
if( (fd=open(FIFO_NAME, open_mode)) < 0 )
{
printf("\nError: Named pipe cannot be opened\n"); exit(0);
}
while(1)
{
n=read(fd, r, MAXSIZE); if(n > 0)
printf("\nConsumer read: %s", r);
}
} /*main close*/
Producer program:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#define MAXSIZE 10
#define FIFO_NAME "myfifo"
55
30
int main()
{
int fifoid; int fd, n; char *w;
int open_mode;
system("clear");
w=(char *)malloc(sizeof(char)*MAXSIZE);
open_mode=O_WRONLY;
fifoid=mkfifo(FIFO_NAME, 0755);
if(fifoid==-1)
{
printf("\nError: Named pipe cannot be Created\n"); exit(0);
}
if( (fd=open(FIFO_NAME, open_mode)) < 0 )
{
printf("\nError: Named pipe cannot be opened\n");
exit(0);
}
while(1)
{
printf("\nProducer :"); fflush(stdin);
read(0, w, MAXSIZE);
n=write(fd, w, MAXSIZE);
if(n > 0)
printf("\nProducer sent: %s", w);
} /*main close*/
Output:
56 30
EXPERIMENT NO: 21 Date:
Aim:-Write client server programs using c for interaction between server and client
process using Unix Domain sockets
Algorithm:-
Sample UNIX server
Step 1:define NAME "socket"
Step 2: sock = socket(AF_UNIX, SOCK_STREAM, 0);
Step 3:if (sock < 0) perror("opening stream socket"); exit(1);
step4: server.sun_family = AF_UNIX;
strcpy(server.sun_path, NAME);
if (bind(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un)))
{
perror("binding stream socket"); exit(1);
}
step 5: print ("Socket has name %s\n", server.sun_path);
listen(sock, 5);
step 6: for (;;)
{
msgsock = accept(sock, 0, 0);
if (msgsock == -1)
perror("accept");
else
do { bzero(buf, sizeof(buf));
if ((rval = read(msgsock, buf, 1024)) < 0)
Step 7:stop
Programs:
Server.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h> 57
30
int connection_handler(int connection_fd)
{
int nbytes;
char buffer[256];
nbytes = read(connection_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM CLIENT: %s\n", buffer);
nbytes = snprintf(buffer, 256, "hello from the server");
write(connection_fd, buffer, nbytes);
close(connection_fd);
return 0;
}
int main(void)
{
struct sockaddr_un address;
int socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf("socket() failed\n");
return 1;
}
unlink("./demo_socket");
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(bind(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("bind() failed\n");
return 1;
}
58
30
if(listen(socket_fd, 5) != 0)
{
printf("listen() failed\n");
return 1;
}
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
child = fork();
if(child == 0)
{
/* now inside newly created connection handling process */
return connection_handler(connection_fd);
}
/* still inside server process */
close(connection_fd);
}
close(socket_fd);
unlink("./demo_socket");
return 0;
}
Client.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
struct sockaddr_un address;
int socket_fd, nbytes;
char buffer[256];
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(connect(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("connect() failed\n");
return 1;
}
nbytes = snprintf(buffer, 256, "hello from a client");
write(socket_fd, buffer, nbytes);
close(socket_fd);
return 0;
}
Assignment:
Sno Task Date Sign Remark
1 Write a program to demonstrate getting and setting the socket options
through socket related system call
2 Write a program to demonstrate bind system call.
60
30
EXPERIMENT NO: 24 Date:
Aim:-Write a C program that illustrates two processes communicating using Shared memory
Algorithm:-
step1.Start
step 2.Include header files required for the program are
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
step 3.Declare the variable which are required as
pid_t pid
int *shared /* pointer to the shm */
int shmid
step 4.Use shmget function to create shared memory
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the shared memory identifier associated with key The
argument key is equal to IPC_PRIVATE. so that the operating system selects the next
available key for a newly created shared block of memory. Size represents size of
shared memory block Shmflg shared memory permissions which are represented by octalinteger
shmid = shmget (IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
print the shared memory id
step 5.if fork()==0 Then
begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2
print *shared sleep(2)
print *shared
end
step 6.else
begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared)
print *shared sleep(1) *shared=30
printf("Parent value=%d\n", *shared);
sleep(5)
shmctl(shmid, IPC_RMID, 0)
end
step 7.stop.
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
61
30
int main(void) {
pid_t pid;
int *shared; /* pointer to the shm */ int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666); printf("Shared Memory
ID=%u",shmid);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0, 0);
printf("Child pointer %u\n", shared); *shared=1;
printf("Child value=%d\n", *shared); sleep(2);
printf("Child value=%d\n", *shared); } else { /* Parent */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0, 0);
printf("Parent pointer %u\n", shared); printf("Parent value=%d\n", *shared); sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared); sleep(5);
shmctl(shmid, IPC_RMID, 0);
}
Viva questions
1. define shared memory
2. what are file locking functions. 3.what are shared memory system calls.
4.define internet domain sockets
5.Difference between internet and unix domain sockets.
Assignment:
Sno Task Date Sign Remark
1 Write a program to demonstrate communication of two different process
via shared memory
2 Write a program to demonstrate that the shared memory created will be
available even after the process which created is exited.
30