Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unix

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Lab Manual

Master of Computer Applications

Course: UNIX SYSTEM PROGRAMMING

Course Code: 2MCA8

Semester: II

Scheme: CBCS scheme

Year of Implementation: 2021-22

List of Programs
S. Page No.
No. Title of Program
1. UNIX Commands
Write a shell script that displays list of all the files in the
2. current directory to which the user has read, write and execute
permissions.
Write a shell script that accepts a list of file names as its
3. arguments, count and reports the occurrence of each word that
is present in the first argument file on other argument files.
Write a shell script that accepts one or more file name as
4. arguments and converts all of them to uppercase, provided they
exist in the current directory.
Write grep commands to the following:
5. a. To select the lines from a file that has exactly 2 characters.
b. To select the lines from a file that has more2 than one blank
spaces.
Write a shell script which accepts two file names as arguments.
6. Compare the contents. If they are same, then delete the second
file.
Write a shell script
7. a. to count number of lines in a file that do not contain vowels.
b. to count number of characters, words, lines in a given file.
8. Write a shell script to list all the files in a given directory.

9. Write a shell script to display list of users currently logged in.


Write a shell script to read three text files in the current
10. directory and merge them into a single file and returns a file
descriptor for the new file.
PART B
11.
Write a program to copy a file into another using system calls.
12. Write a program using system call: create, open, write, close,
stat, fstat, lseek.
Write a program to create a child process and allow the parent
13. to display “parent” and the child to display “child” on the
screen.
14. Write a program to create a Zombie process.

15. Write a program to implement inter process communication


using pipes.
Simulate the following CPU scheduling algorithms
16. a. Round Robin
b. SJF
17. Write a program that illustrates file locking using semaphores.

18. Write a program that implements a producer-consumer system


with two processes (using semaphores).
19. Write a program that illustrates inter process communication
using shared memory systemcalls.
Write a program that illustrates the following:
20. a. Creating message queue.
b. Writing to a message queue
c. Reading from a message queue
Instructions to Students

1. Do not change computer settings or backgrounds


2. Enter the computer lab on time and work quietly
3. No food or drinks near the computers
4. Please POWER DOWN all computers and monitors before leaving the Lab
5. Computers and peripherals are not to be moved or reconfigured without approval of Lab
and Classrooms staff.
6. Behaviour and activities that disturb other users or disrupt the operations of the lab are not
allowed. This includes, but is not limited to: physical activities such as "rough-housing,"
loud music, etc.
7. Violation of any of the above rules may result in disciplinary action and the loss of lab
privileges.

Part A
Linux Commands
date: To display the system date
Command:
$date
Output:
Tue Oct 10 22:55:01 PDT 2021

Command:
$date -u
Output :
Wed Oct 11 06:11:31 UTC 2021

Command:
$date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010

history: Display previously executed commands

$ history 3
2000 ls
2001 ls –l
2002 who

man: Displays commands with its available option.

$ man printf

Displays the manual page of printf.


who: Display the current user who are working on unix operating system.
hduser@mahesh-Inspiron-3543:~$ who
hduser tty7 2018-03-21 19:08 (:0)

finger: Finger command is a user information lookup command which gives details of all the
users logged in. This tool is generally used by system administrators. It provides details like login
name, user name, idle time, login time, and in some cases their email address even.

$finger manav
cal: To display the calender of the year or month.

cat: One of its most commonly known usages is to print the content of a file onto the standard
output stream

2. Write a shell script that displays list of all the files in the current directory to which the
user has read, write and execute permissions.

Program
# Shell script to display list of file names
# having read, Write and Execute permission
echo "The name of all files having all permissions :"

# loop through all files in current directory


for file in *
do

# check if it is a file
if [ -f $file ]
then

# check if it has all permissions


if [ -r $file -a -w $file -a -x $file ]
then

# print the complete file name with -l option


ls -l $file

# closing second if statement


fi
# closing first if statement
fi
done

3. Write a shell script that accepts a list of file names as its arguments, count and reports the
occurrence of each word that is present in the first argument file on other argument files.

if [ $# -lt 2 ]
then
echo "produce atleast two command line arguments"
else
tr " " "
" < $1 > temp
shift
for i in $*
do
tr " " "
" < $i > temp1
y=`wc -l < temp`
j=1
while [ $j -le $y ]
do
x=`head -n $j temp | tail -1`
c=`grep -c "$x" temp1`
echo $x $c
j=`expr $j + 1`
done
done
fi

4. Write a shell script that accepts one or more file name as arguments and converts all of them to
uppercase, provided they exist in the current directory.

if [ $# -lt 1 ]
then
echo "Enter command line arg"
exit 0
fi
for f in $*
do
if [ -e $f ]
then
cat $f | tr "[a-z]" "[A-Z]" > tmp
mv tmp $f
else
echo "File $f does not exist"
fi
done
5. Write grep commands to the following:
a. To select the lines from a file that has exactly 2 characters.
b. To select the lines from a file that has more2 than one blank spaces.

A. grep ^..$ dhan1


B. grep " *.* " file_in

6. Write a shell script which accepts two file names as arguments. Compare the contents. If
they are same, then delete the second file.

#!/bin/ksh
echo "Enter first File name"
read filename1
echo "Enter second file name"
read filename2
diff $filename1 $filename2 >/dev/null
if [ `echo $?` -eq 0 ]
then
echo "Both the file content is Same & the second file is deleted
"
rm $filename2
else
echo "File content is Different"
fi

7. Write a shell script


a. to count number of lines in a file that do not contain vowels.
b. to count number of characters, words, lines in a given file.

echo "Enter the file name to check no of line and word and character
"
read file
number_of_lines=`wc -l < $file`
number_of_character=`wc -c < $file`
number_of_words=`wc -w < $file`
echo "Number of lines: $number_of_lines"
echo "Number of words: $number_of_words"
echo "Number of character: $number_of_character"

8. Write a shell script to list all the files in a given directory.


# !/bin/bash
echo "enter directory name"
read dir
if [ -d $dir ]
then
echo "list of files in the directory"
ls -l $dir
else
echo "enter proper directory name"
fi

9. Write a shell script to display list of users currently logged in.

line () {
echo "*************************************************"
}

echo "Currently logged on users:"


who
line

10 Write a shell script to read three text files in the current directory and merge them into a single
file and returns a file descriptor for the new file.

echo ^^Enter file nam1^^


read f1
echo "Enter file name2"
read f2
echo "Enter file name3"
read f3
echo ^^Enter resultant file name^^
read f4
cat $f1 $f2 $f3 > $f4
echo "New file $f4 created successfully"
PART B

1. Write a program to copy a file into another using system calls.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

void main()
{
char buf;
int fd_one, fd_two;
fd_one = open("first_file", O_RDONLY);
if (fd_one == -1)
{
printf("Error opening first_file make sure that you
have created --- first_file\n");
close(fd_one);
return;
}
fd_two = open("second_file",
O_WRONLY | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IR
OTH);
while(read(fd_one, &buf, 1))
{
write(fd_two, &buf, 1);
}
printf("Successful copy");
close(fd_one);
close(fd_two);
}

2. Write a program using system call: create, open, write, close, stat, fstat, lseek.

3. Write a program to create a child process and allow the parent to display “parent” and the child
to display “child” on the screen.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int pid;
int status;
printf("Hello World!\n");
pid = fork( );
if(pid == -1) /* check for error in fork */
{
perror("bad fork");
exit(1);
}
if (pid == 0)
printf("I am the child process.\n");
else { wait(&status); /* parent waits for child to finish */
printf("I am the parent process.\n");
}
}

4. Write a program to create a Zombie process.


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
// Create a child process
int pid = fork();
if (pid > 0)
printf("in parent process");
// Note that pid is 0 in child process
// and negative if fork() fails
else if (pid == 0)
{
sleep(3);
printf("in child process");
}
return 0;
}

5. Write a program to implement inter process communication using pipes.

#include<stdio.h>
#include<unistd.h>

int main() {
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
pid = fork();

// Child process
if (pid == 0) {
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 1 is %s\n", readmessage);
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 2 is %s\n", readmessage);
} else { //Parent process
printf("Parent Process - Writing to pipe - Message 1 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
printf("Parent Process - Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));
}
return 0;
}

6. Simulate the following CPU scheduling algorithms


a. Round Robin
b. SJF

#include<stdio.h>

int main()
{

int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];
flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);

return 0;
}

SJF

#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);

printf("\nEnter Burst Time:\n");


for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}

//sorting of burst times


for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0;

for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n;
total=0;

printf("\nProcesst Burst Time \tWaiting TimetTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("\np%dtt %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n;
printf("nnAverage Waiting Time=%f",avg_wt);
printf("nAverage Turnaround Time=%fn",avg_tat);
}

9. Write a program that illustrates inter process communication using shared memory system
calls.
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


int shmid = shmget(key,1024,0666|IPC_CREAT);

// shmat to attach to shared memory


char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
gets(str);

printf("Data written in memory: %s\n",str);

//detach from shared memory


shmdt(str);

return 0;
}

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


int shmid = shmget(key,1024,0666|IPC_CREAT);

// shmat to attach to shared memory


char *str = (char*) shmat(shmid,(void*)0,0);

printf("Data read from memory: %s\n",str);

//detach from shared memory


shmdt(str);

// destroy the shared memory


shmctl(shmid,IPC_RMID,NULL);

return 0;
}

10. Write a program that illustrates the following:


a. Creating message queue.
b. Writing to a message queue
c. Reading from a message queue
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10

// structure for message queue


struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;

// ftok to generate unique key


key = ftok("progfile", 65);

// msgget creates a message queue


// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
message.mesg_type = 1;

printf("Write Data : ");


fgets(message.mesg_text,MAX,stdin);

// msgsnd to send message


msgsnd(msgid, &message, sizeof(message), 0);

// display the message


printf("Data send is : %s \n", message.mesg_text);

return 0;
}

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>

// structure for message queue


struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{
key_t key;
int msgid;

// ftok to generate unique key


key = ftok("progfile", 65);

// msgget creates a message queue


// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);

// msgrcv to receive message


msgrcv(msgid, &message, sizeof(message), 1, 0);

// display the message


printf("Data Received is : %s \n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);

return 0;
}

You might also like