PRACTICAL 1 AIM: To study and implement various linux commands. THEORY: Linux is an open source kernel developed by Linus torvalds. It is a widely used kernel and together with other GNU add ons together forms GNU/Linux. Many versions of linux like ubuntu, red hat, fedora are available for free. Linux is a powerful tool, and is built to support large number of architectures ranging from x86, to arm to sparx etc. It now also finds itself in small, microcontrolled devices as a tiny Os and also in mobile phones and tablets. Thus linux is a powerful tool implemented in wide range of devices. Linux is a UNIX like software, a free version of it. It to implements the POSIX standards and APIs. Despite developing a powerful GUI, GNOME and KDE, the main power of linux still lies in CLI: command line interface or terminal.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
With CLI, a special program called the shell is used. A shell acts as an interface between the user and kernel. As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the filemyfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands. The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt ($ on our systems). The terminal in Linux Ubuntu is the bash shell as the basic CLI. On opening a terminal one might see the following syntax: Username @ pcname:~$ The ~ indicates home directory and the $ indicates the non-root user. Her root is like the administrator that has complete control of the system ie access to various system files like device etc. Various commands can be used to implement various functions like file transfer, making directory etc. It also has some more complex uses like create shell, configuring networks, etc. LINUX COMMAND DESCRIPTION username@ubuntu:~$ ls This command lists all the files in the directory (here home directory), but not the files that begin with . . username@ubuntu:~$ ls a This command lists all files including the ones beginning with . . username@ubuntu:~$ ls -l This gives long listing of the file and directories in the current directory. username@ubuntu:~$ pwd This prints the prints the current working directory with the full path. username@ubuntu:~$ cd Directory This changes to the directory mentioned. username@ubuntu:~$ cd .. This returns to the parent of the current directory. username@ubuntu:~$ ls a* This lists all the files that begin with the a character. username@ubuntu:~$ file filename This shows the type of file filename is. username@ubuntu:~$ cat filename This shows the contents of the file filename. username@ubuntu:~$ cd ~ This returns to the home directory. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
username@ubuntu:~$ cp file1 file2 This copies contents of file1 to file2. username@ubuntu:~$ mv file1 file2 This permanently moves the contents of file1 to file2. username@ubuntu:~$ rm file This removes the file. username@ubuntu:~$ rmdir Directory This removes the directory Directory. username@ubuntu:~$ less file This shows contents of file one page at a time. username@ubuntu:~$ head file This shows the first ten lines of file. username@ubuntu:~$ tail file This shows the last ten lines of file. username@ubuntu:~$ grep Keyword file This searches file for Keyword. username@ubuntu:~$ wc option file This counts the number of words/characters/lines in file. The action is decided by option ie foe words it is w. username@ubuntu:~$ command > filename This redirects the standard output to filename ie overwrites it. username@ubuntu:~$ command >>filename This attaches the standard output to the contents of filename. username@ubuntu:~$ command < filename This redirects standard input from filename. username@ubuntu:~$ command1 | command2 This pipes the result of command1 with command 2 without creating temporary files and is faster and cleaner. username@ubuntu:~$ sort <filename This command sorts content of filename or the inputs given . username@ubuntu:~$ who It lists users currently logged in. username@ubuntu:~$ ls *file This lists all the directories that end with file. username@ubuntu:~$ ls ?ouse This lists all the files that match all the characters mentioned but vary only in the first charater. username@ubuntu:~$ man command This gives the manual for the command. username@ubuntu:~$ apropos word This matches command with word in their man page. username@ubuntu:~$ echo text This displays the text. username@ubuntu:~$ ps This returns the current working processes or programs. username@ubuntu:~$ id This gives the user id. username@ubuntu:~$ free This frees space. username@ubuntu:~$ top This gives all the processes that are running in the CPU. username@ubuntu:~$ find . opt1 set of files op2 This finds patterns specified by options op1 like name in set of files and op2 which can be print or ls etc. username@ubuntu:~$ whereis file Gives all location instances of file. username@ubuntu:~$ cal Displays Calender.
username@ubuntu:~$ file filename Displays type of file filename is. username@ubuntu:~$ zip op file.zip files Creates a zip file of the files given in argument. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
username@ubuntu:~$ unzip file.zip Unzips a zip file. username@ubuntu:~$ tar cvf filename.tar files/directories Creates a tar (archive) file of the following files and directories. Parameters like t, x, cz, xz can be used to read, extract, compress and expand the tar file. username@ubuntu:~$ shutdown op arg To shutdown or restart the system. The op can be r or h for restart or halt. The arg specifies the time, now for immediate. username@ubuntu:~$ rev file Reverses the contents of file. username@ubuntu:~$ chmod no filename Changes the mode of the file. A file can have three modes read, write and execute. Also a file can have modes for owner, group and other. Thus r, w, and x are represented as 1 or 0. The number is made of the decimal for the three types hence three digit number.
Conclusion: Thus we have studied some frequently used linux commands. It shows the power of the linux terminal. Operations like pipe, >>, << make it simple to join concatenate commands and make variations of them. Linux has a very structured file system with various file arranged in tree like structure. All files can be read, write and executed unlike windows which has different file format for execution (exes). Shells are powerful and provide a lot of abstraction between user and kernel, thus aiding to security. Name of the Assessing Faculty: Professor Udmale
Signature: _________________________
Dated: ________________
************
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 2 AIM: To create and execute a shell program to count the number of lines, words and bytes of a file. THEORY: Shell scripts are scripts created by user, to create their own commands. The shell provides you with an interface to the UNIX system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program's output. A shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of shells, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized commands and functions. The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by a pound sign, #, describing the steps. There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive amounts of data, files to read and store data, and variables to read and store data, and the script may include functions. Shell scripts and functions are both interpreted. This means they are not compiled. Thus they are executed by executing command ./shellname. Shell scripts can be edited in any editor like vi, nano, emacs, gedit etc. The shell scripts mode must be changed to read write execute. In shell scripts comments can be written using #. Semicolons need not be written; instead one can write it on next line. We can also use and define variables to be used in the program. No data type needs to be specified. A variable can be accessed using the $ operator. We can also use echo to display a variable or string. PROGRAM: #written in gedit file test1.sh #echo Hello echo Hello World #create variable and assign it wc command. var1=`wc one.txt` #echo variable Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
echo $var1 OUTPUT:
Conclusion: Thus we have studied and implemented a shell script to display number of lines, words and bytes in a file. Shell scripts allow users to make their own commands for a purpose that cannot be simply solved by standard commands. Its dynamic initialization of variables simplifies programming and creating better scripts. Name of the Assessing Faculty: Professor Udmale
Signature: _________________________
Dated: ________________
************ Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 3 AIM: To study basics of shell programming. THEORY: Shell programs provide many control statements to alter the flow of the program. They provide if else, for and while loops. Linux also provides several useful commands to test condition and expression. These include comparisons or file manipulation. Some commands provide evaluation of integer expressions and performing necessary integer arithmetic. Pipes are useful to connect multiple commands as a single command and redirect input output. Several other commands are used to manipulate the data and segregate the data so as to provide only certain parts of output. Program1: To create a file using shell command. if test -e $1 then echo "File already exists" else touch $1 echo "File created" fi In this program if and test are used. The syntax of an if expression is if exp then code fi. Nesting of if- else statements can be done. To pass user parameters, like name of file to be created, we use command line arguments. Each command line argument can be referenced by variables like $0, $1, and so on. $0 refers to the command and $1 the first parameter. The test command is used for testing various expressions. Here it test whether the file to be created already exists or not. This is done using e option. If so, then there is no need to create new file. Is not, then we use the touch command to create the file $1. The output is as shown. The permissions of the shell program must be changed for by default it is only read write. We can change the permissions using the chmod command. The shell can be then executed by ./ command. Using ls we can verify the changes. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 2: To Check If an integer is positive or negative. if test $1 -lt 0 then echo "Number is negative" else echo "Number is positive." fi This program is a simple one. We use the test command and compare two integers. Several options like eq, -lt, -le etc exist to help in the comparison of various integer expressions. Here we use the less than or lt option. The number is passed as a command line argument by the user. The number is tested if it is less than zero. If so then the number is negative else the number is positive. Note here that test works only on integer arguments. Decimal numbers will give error. The output is shown. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 3: To Give A File Executable Permission: if test -x $1 then echo "File already has execute permission" else chmod 777 $1 echo "Executable permissions given" fi We accept the file name here as a command line argument. We first test if the file is already an executable using the x option of test. If so we simply echo that the file already has executable permissions. If not so then we use the chmod command and change it to an executable. The output is shown. We can verify mode of file using the ls command with the l option. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 4: To Remove Executable Permissions From A File. if test -x $1 then echo "Removing exec permission..." chmod 666 $1 else echo "It doesnt hav exec permission" fi
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
In this shell script, we first check for the executable permissions of the file. If it is an executable then we remove the executable permission using the chmod command. The file name is passed as a command line argument. The output is a shown.
PROGRAM 5: To Find The Command Executed Maximum Times. echo "The command executed maximum times is:" history | cut -c 8- | cut -d " " -f 1 | sort | uniq -c | sort -n | tail -1 The above program implements use of pipes. Pipes are used to redirect output of one command as input of other thereby eliminating the need for temporary files to be made for storing output. The first step would be to access the command logs. The command log can be accessed via the history command. The history command however lists the commands in a chronological order. Also we only need the name of the command not the arguments or the index no. Thus to Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
segregate the output we use the cut command. We pipe the output of the history command. First we remove the index number. We cut the input by character using the c option. It cuts the input character by character. Then it selects the columns where the command begins. Now we again pipe this output as an input for another cut operation. This cut operation separates and selects the first space, thereby getting command name. We then sort it using the sort command. Then we use uniq command c. This displays the number of occurrences of that command. Then we sort it again by numbers and then we select the last item of the sorted list which is the most frequently used command.
PROGRAM 6: To Count The Number Of Files And Directories In The Current Folder. var=1 f=0 d=0 for a in `ls` do if test -f $a then f=`expr $f + $var` else if test -d $a then Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
d=`expr $d + $var` fi fi done echo "NO OF FILES IS:"$f echo "NO OF DIRECTORIES IS:"$d In the above program we use for loops. We initialize var to 1 and file counter f and directory counter d as 0. The for loop syntax is used, where variable a can be used to hold the various elements passed in the loop. They can be integers, decimals, command outputs or any type of data. We use the ls command as input. Each input is then checked if it is a file or directory using the test command. If so then their respective counters are incremented. Finally they are displayed.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 7: To Perform Arithmetic Operations On Integer
echo "Addition of the two no is:"`expr $1 + $2` echo "Subtraction of the two no is:"`expr $1 - $2` echo "Multiplication of the two no is:"`expr $1 \* $2` if test $2 -eq 0 then echo "Second argument is negative....Operation terminated." else echo "Division of the two no is:"`expr $1 / $2` fi if test $2 -eq 0 then echo "Second argument is negative....Operation terminated." else echo "Remaider of the two no is:"`expr $1 % $2` fi In this program we perform arithmetic operations on integers. We pass integers as command line arguments. We use the expr command to perform the operations. However we can only perform arithmetic operations on integers. We also use if statement to check if the second argument is zero and if so we do not perform the operation. Multiplication requires an escape character \ since * has a predefined usage in shell scripting. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Conclusion: Thus we have studied and implemented several shell scripts that perform various functions. Shell scripts are powerful tools and along with the commands provided by linux can be used to make more powerful and simple commands. Piping also helps in simplifying tasks by making long tasks simpler, shorter and efficient. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************ Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 4 AIM: To study shell programs and file manipulation using shell programs. THEORY: PROGRAM 1: To find the most frequently used word in a text file. echo "The most frequently used word is::::" x=`cat freq.txt | tr [:punct:] ' '` for i in $x do echo $i done | tr 'A-Z' 'a-z' | sort |uniq -c| sort -n | tail -1
In this program we use the cat command. cat command displays the contents of the file. tr command is used to replace certain text in the input (here file). The tr replaces punctuations with blank. The for loop is used to analyze each word. The tr then replaces uppercase letters with lowercase letters. The words are sorted and then same words are gathered together. The list is again sorted and then the last entry is selected as it is the most frequent command used. OUTPUT:
PROGRAM 2: To find the largest file in the directory. name=null high=0 for a in `ls` do if test -f $a then size=`wc -c $a|cut -d " " -f 1` if test $high -eq $size then name=$name" "$a else if test $high -lt $size Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
then high=$size name=$a fi fi fi done echo "Biggest File::"$name " with Size::" $high
In this program we use the ls and wc command. We use the ls command as input for for loop. The wc command has a c option to determine the size of the file. The name is cut out of the output. If the current file size is greater than the previous highest, then the new highest is replaced and rewritten. Else if it is equal, it is concatenated with the current biggest file. Test is performed in the beginning whether the entry is a file or not. OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 3: To convert the first letter in a new line to its uppercase letter.
PROGRAM:
echo -n "" > temp2.txt while read line
do
var1=`echo $line | cut -d " " -f 1` var2=${#var1} if test $var2 -eq 1 then var=`echo ${line:0:1} | tr 'a-z' 'A-Z'`" "`echo ${line:1:${#line}}` else var=`echo ${line:0:1} | tr 'a-z' 'A-Z'``echo ${line:1:${#line}}` fi
In this program we use the read command. This command is used with the while loop, and input is redirected from a text file. The basic algorithm is finding the first letter. This is done by creating substrings, and translating it to uppercase, using tr command. Then this letter is concatenated with the rest of the string. In case the first line has its first word as a single letter, this method needs some modification, and a space must be added between the two substrings. This result is written in a temporary file which is cleared in the beginning, and then transferred to the original file.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
PROGRAM 4: To find the middle line of a file PROGRAM: zero=0 echo "The middle line is ::" var=`wc -l mid.txt | cut -d " " -f1` tes=`expr $var % 2` var=`expr $var / 2` var=`expr $var + 1` if test $tes -eq $zero then head -$var mid.txt | tail -2 else Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
head -$var mid.txt | tail -1 fi In this program we use the head and tail linux commands. We first use wc with l option to find the number of lines in a file. If the number of lines is odd then we only have one middle line of the text file. Else we have two middle lines. If the remainder of no of lines when divided by two is zero, we use the head facility and segregate the first half lines from the file. We pipe this output as the input of tail command, and select the last two lines, which are the middle lines. If the number of lines is odd, then we simply take the last line in tail command which will be the middle line of the file. OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 5: To store the last word of a file in one file, and the rest in others.
PROGRAM:
echo -n "" > mid3.txt
echo -n "" > mid4.txt
count=0
var2=""
while read line
do
var=`echo $line | wc -w`
var2=`expr $var - 1`
echo $line | cut -d " " -f 1-$var2 >> mid3.txt
echo $line | cut -d " " -f $var >>mid4.txt
done < mid2.txt
In this program, we first read the file line by line. On encountering the last line of the file, we use a for loop to read the line word by word. If we encounter the last word we write it in another file else we append the rest of the letters to the other file. We write the words or lines in the file using the echo command and then redirect the output to a file.
The rest of the lines will be appended to the other file.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
CONCLUSION: Thus we studied file manipulation using shell scripts. This shows how powerful the shell is, and along with its rich library of built in commands, several complex commands can be made and used. The while loop helps in reading the file line by line. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 5 AIM: To implement various linux system calls. THEORY: An operating system usually provides an abstract layer between hardware and application programs. A user usually executes in user level mode, and the kernel is not continuously executing in the processor. But once an application requires some hardware facility, like disk read or sending data to a terminal, it needs the kernel to actually implement it at hardware level. The application makes a system call, it traps the kernel and passes the functionality to the kernel, the kernel executes the command and returns back the functionality to the kernel. This protects the hardware from the user application. System calls are interrupts at assembly level and the microprocessor changes it PC count to the interrupt vector and returns back after completing the task. In unix systems, a system call is a C function. All the system calls are in unistd and sys/types header file. Some system calls include fork, read, write, getpid etc. Fork system call: Fork system call is used to create a child process. To use it one must include the unistd and the sys/types header file. When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. The child process executes from the next instruction and it and the parent start executing a new process. The fork returns pid_t data type. For parent it is the process id of the newly created process, else for child it is zero. This is how we can make the child and parent execute different codes. The fork system call does not take any argument. #include<unistd.h> #include<stdio.h> #include<sys/types.h> int main() {int pid,x; pid=fork(); if(pid==0) {printf("Child 1 ..\n"); } else {printf("Second:\n"); x=fork(); Operating Systems Lab, 2013-14
Getpid and getppid: These two system calls are used to get the process id of the process and its parent. Both the functions return pid_t data type. Note that the pid changes every time one executes the program, unless the program that is still running (bash, init etc). The system call can be particularly helpful to identify a process, since the OS identifies #include<unistd.h> #include<sys/types.h> #include<stdio.h> int main() {int pid; pid=fork(); if(pid==0) {printf(":This is Child:\n"); Operating Systems Lab, 2013-14
Wait system call: This function blocks the calling process until one of its child processes exits or a signal is received. wait() takes the address of an integer variable and returns the process ID of the completed process. Some flags that indicate the completion status of the child process are passed back with the integer pointer. One of the main purposes of wait() is to wait for completion of child processes. It can obtain information about the child whose state has changed. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
The exit status returned by a child process typically indicates whether the process terminated normally or abnormally. For normal termination, this status also includes the exit code (usually a small integer value) that the process returned to the system. A child process that terminates but is never waited on by its parent becomes a zombie process. Such a process continues to exist as an entry in the system process table even though it is no longer an actively executing program. Such situations are typically handled with a special "reaper" process that locates zombies and retrieves their exit status, allowing the operating system to then deallocate their resources. Similarly, a child process whose parent process terminates before it does becomes an orphan process. Such situations are typically handled with a special "root" (or "init") process, which is assigned as the new parent of a process when its parent process exits. This special process detects when an orphan process terminates and then retrieves its exit status, allowing the system to deallocate the terminated child process. wait returns the pid of the last child to finish execution. Two header file : sys/types.h and sys/wait.h must be included to use various wait functions. #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> #include<stdio.h> int main() {int pid,x,status=0,c; pid=fork(); if(pid==0) {printf("First Child.....Status:%d Return Value %d PID:%d PPID:%d\n",status,c,(int)getpid(),(int)getppid());
Sleep: The sleep function causes the calling process to sleep ie halt for some time, the time specified in seconds as the argument of the finctions. #include<sys/types.h> #include<unistd.h> #include<stdio.h> int main() {int pid,i; pid=fork(); if(pid==0) {for(i=0;i<5;i++) {printf("Child Awake :: %d\n",i);sleep(1);} } else {for(i=0;i<5;i++) {printf("Parent Awake :: %d\n",i);sleep(2);} } }
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
CONCLUSION: Thus we have studied some system calls implemented in the Unix type systems. System calls provide a level of abstraction from the hardware while making it simple to perform important system functions provided by the kernel. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************ Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 6 AIM: To study various system calls. THEORY: System calls are used to request various resources from the kernel without directly affecting the resources. We implement the wait system call for multilevel hierarchy of processes and also see how the processes use common resources. PROGRAM 1: To implement multilevel hierarchy of processes PROGRAM: #include<unistd.h> #include<sys/types.h> #include<stdio.h> #include<sys/wait.h> int main() {int p,r; p=fork(); if(p==0) {printf("This is child newly born\n"); r=fork(); if(r==0) {printf("This is grand Child newly born\n"); } else{wait(0); printf("THis is child after fork\n"); } } else {wait(0); printf("This is parent after fork\n"); } }
Here the parent creates a child and the child too creates a grandchild. The wait command allows the grandchild to finish first followed by the child and finally the parent.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
PROGRAM 2: To implement a program showing the use of resource by child and parent: PROGRAM: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main() {int p; int i=0;int j=9; printf("Value of i,j & Address initially is::%d %p %d %p\n",i,&i,j,&j); p=fork(); if(p==0) {printf("THis is Child\n"); i+=10;j+=10; printf("New value of i,j and address after add 10::%d %p %d %p\n",i,&i,j,&j); } else{ printf("This is parent\n"); i-=5;j-=5; Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
printf("New value of i,j and address after sub 5::%d %p %d %p\n",i,&i,j,&j); } }
Here the variable i is initialized to zero and j to 9. When a fork call is made, the child increments i and j by 10 while the parent decrements it by 5. The addresses of the variables area also printed.
OUTPUT:
PROGRAM 3: To implement file functions and study file sharing.
In this program we use inbuilt C functions. fopen() function is used to open a file for use. Its parameters include the path of the file and the mode in which it is to be opened. It returns a File * if the path exits else it returns NULL. The fread() function is used to read contents of file. Its parameters include a pointer to store the read data, the size of data , the number of data items of size specified to be read and the file pointer. The ftell function returns a long integer specifying the current file pointer position. Its parameters include the file pointer. Here in the program the child, grandchild and the parent all read the same file. However the parents wait for their children to complete.
OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
CONCLUSION: Thus we have seen how processes use resources. Usually the local resources and variables are copied for all child processes. However resources like files are shared and used by various processes. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************ Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 7 AIM: To study the execvp command and directories in unix and simulate copy, grep and ls in C. THEORY: Program 1: To use execvp so that the child will execute a different program from the parent Program: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main() {int pid; printf(This is main process::%d %d\n,(int)getpid(),(int)getppid()); pid=fork(); if(pid==0) {printf(This is child process::%d %d\n,(int)getpid(),(int)getppid()); execvp(/home/harshal/Lin_C/b.out,\0); } else {wait(0); printf(This is main after producing child::%d %d\n,(int)getpid(),(int)getppid()); } }
Usually after the fork command, the child continues to execute the same code as the parent. However using execvp the process image can be changed ie the code and data can be changed and a new program will be executed by the child. The exec families of programs are the programs which cause this process image to be changed. The execv family provides an array of pointers to null terminated list to represent the argument list of the new program. The function only returns if an error occurs. The p in the exec suggests that the function use the PATH variable to find the file. The arguments include path and arguments.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Output:
Program 2: To simulate ls command in C using directory functions. Program: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<dirent.h> int main() {char s[40];//FILE *fin,*fout; DIR *dir;struct dirent *dr; printf(Enter source directory:\n); scanf(%s,s); //printf(Enter destination directory:\n); //scanf(%s,d); dir=opendir(s); if(dir==NULL) {printf(Directory not found\n);
In this program we use the DIR data type, and the structure dirent. Dirent header file include the dirent structure. The opendir and readdir are used to read the directories. Here the dirent structure reads the file in the directory. Output:
Program 3: To simulate the copy command in C. Program: #include<stdio.h> #include<dirent.h> Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
#include<unistd.h> #include<sys/types.h> #include<stdlib.h> int main() {DIR *ds,*dd;char s[60];char d[60];FILE *fin,*fout; struct dirent *dob; printf(Enter source directory(Pls add / at the end)::\n); scanf(%s,s); printf(Enter destination directory(Pls add / at the end)::\n); scanf(%s,d); ds=opendir(s); dd=opendir(d); if(ds==NULL) { printf(Error in source directory:No such directory exists!!\n); exit(0); } if(dd==NULL) {printf(Error in destination directory:No such directory exists!!\n); exit(0); } while((dob=readdir(ds))!=NULL) {char *a,*b;char d2[60],s2[60]; strcpy(d2,d); a=strcat(d,dob->d_name); //printf(%s\n%s\n,a,dob->d_name); strcpy(s2,s); b=strcat(s,dob->d_name); //printf(%s\n%s\n,b,a); fin=fopen(b,r); fout=fopen(a,w); char buff[60]; while(fgets(buff,sizeof(buff),fin)!=NULL) fputs(buff,fout); strcpy(s,s2); strcpy(d,d2);
} }
This program copies the contents of one directory to another previously formed directory. The dirent structure is used to read the name of the files, appended to the input directories. Fopen is used to open a stream and fgets is used to read the file line by line. The fputs is used to write to the newly created file in the other directory. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Fgets uses parameters like the buffer where the line is stored, the size of the buffer and the File stream. Fputs uses parameters like the File stream and the buffer. The opendir has the pathname of the directory. It returns NULL if the directory does not exist. The dirent structure has a inode and a buffer containing the name of the files in the directory. OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Program 3: To simulate grep program in C Program: #include<stdio.h> #include<dirent.h> #include<stdlib.h> int main() {FILE *f;DIR *d;struct dirent *dd; char pat[60];char di[60]; printf(Enter pattern to be found:\n); scanf(%s,pat); printf(Enter directory to be searched:\n); scanf(%s,di); d=opendir(di); if(d==NULL) {printf(No such directory exists!\n); exit(0); } while((dd=readdir(d))!=NULL) Operating Systems Lab, 2013-14
//printf(%s\n,a); f=fopen(a,r); /*while(*a!=\0) printf(%c,*a++); printf(\n);*/ if(f==NULL){printf(Erron\n);exit(0);} while(fgets(g,sizeof(g),f)!=NULL) {int found; //printf(Line is %s\n,g); found=search(g,pat); if(found==1){printf(\nFound in file:%s\nThe Line is:%s,a,g);} } } printf(\n); } int search(char a[],char b[]) { //printf(This is %s and %s,a,b); int i=0,j=0;int flag=0; while(a[j]!=\0) { if(b[i]==\0) {i=0; flag=1; } if(b[i]==a[j]) { i++;j++;continue; } else{ j++;i=0; } } return flag; }
In this program we simulate grep using directory structures. This program finds in the directory submitted by the user, where and in which files the pattern occurs. If it occurs it prints the file name along with the line where it is found. Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
The various files are read line by line. If the pattern is a substring of the line the line is printed. This process is used for the entire line. OUTPUT:
CONCLUSION: Thus we have studied the execvp function and implemented directories in C, simulating the ls grep and cp copy. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************ Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 8 AIM: To use the perror function and the pipe function in C. THEORY: Program 1: To use perror function in C Program: #include<unistd.h> #include<sys/types.h> #include<stdio.h> int main() { FILE *f; f=fopen("test.txt","r"); perror("The error is");
}
perror() function is used to interpret the error number of a error, which is set when errors occur. It takes a constant void pointer, and the string passed is printed along with a colon at the end and print the error corresponding to the error number in the sys_errlist[].
OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Program 2: To use pipe in C
#include<unistd.h> #include<stdio.h> #include<sys/types.h> int main() {int fd[2]; pipe(fd); int pid; pid=fork(); if(pid==0){int buf=0; printf("THis is child who is consumer\n"); while(read(fd[0],&buf,sizeof(buf))<1){printf("Patiently Waiting\n");} printf("Buffer value is %d\n",buf); buf-=5; printf("After consumption buffer value is %d\n",buf); write(fd[1],&buf,sizeof(buf)); } else{ int n=0; printf("Initially the buffer value is %d\n",n); n+=10; printf("Now buffer value is %d\n",n); write(fd[1],&n,sizeof(n)); wait(0); printf("This is after wait!\n"); read(fd[0],&n,sizeof(n)); printf("Now buffer value is(after wait):%d\n",n); } }
In this program the child acts as a consumer and the parent as the producer. The pipe function takes in an integer array of size two as argument, and writes the file descriptor number in the array. The first element points to the read end of the pipe and the second element points to the write end of the pipe. A process can read a data from the read end and write to the write end using the read and write system call.
In this program the parent increments the data element and writes it at the write end. It then waits for the child (consumer) to complete. The child reads the data, decrements the data and then writes the updated value back.
OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
CONCLUSION: Thus we have studied pipe function and the perror function in C. Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________ **********
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 9
AIM: To simulate multiple producer consumer problem is C using fork and pipe
THEORY:
Pipe is used for interprocess communication and is helpful for processes to communicate with each other. Here the parent acts as the producer that produces the buffer and then waits for the child process to consume the buffer.
Program: #include<unistd.h> #include<stdio.h> #include<sys/types.h> int main() {int fd[2]; pipe(fd); int pid; pid=fork(); if(pid==0){ fork(); fork(); int buf=0; printf("THis is child who is consumer with pid %d\n",(int)getpid()); do{read(fd[0],&buf,sizeof(buf));printf("Patiently Waiting %d\n",getpid());}while(buf<=0); printf("Buffer value is %d\n",buf); buf-=5; printf("After consumption by %d buffer value is %d\n",getpid(),buf); write(fd[1],&buf,sizeof(buf)); } else{ int n=0; printf("Initially the buffer value is %d\n",n); n+=10; printf("Now buffer value is %d\n",n); write(fd[1],&n,sizeof(n)); wait(0); n+=20; write(fd[1],&n,sizeof(n)); printf("This is after wait!\n"); read(fd[0],&n,sizeof(n)); printf("Now buffer value is(after wait):%d\n",n); } } Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
CONCLUSION: Thus we have studied multiple producer consumer using pipe in C.
Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
***********
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 10 AIM: To simulate the producer consumer problem and the reader writer problem in java. THEORY: The producer consumer problem and reader writer problems are classical problems on concurrency control. The following problems are implemented in Java using threads. Program 1: Simulating Producer Consumer Problem class prod_con {static int mutex=1; static int buffer; public static void main(String args[]) { new Thread(new Producer("A")).start(); new Thread(new Producer("B")).start(); new Thread(new Consumer("A")).start(); new Thread(new Producer("C")).start(); new Thread(new Producer("D")).start(); new Thread(new Consumer("B")).start(); } } class Producer implements Runnable {String name; Producer(String name) {this.name=name; } public void run() {while(prod_con.mutex==0) {try{ System.out.println("Producer "+this.name+" is waiting mutex , buffer "+prod_con.mutex+" "+prod_con.buffer); Thread.sleep(1000);}catch(Exception e){e.printStackTrace();} } prod_con.mutex=0; prod_con.buffer++; System.out.println("This is producer "+this.name+" n is "+prod_con.buffer); prod_con.mutex=1; } } class Consumer implements Runnable {String name; Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Consumer(String name) {this.name=name; } public void run() {while(prod_con.mutex==0||prod_con.buffer==0) {try{ System.out.println("Consumer "+this.name+" is waiting mutex , buffer "+prod_con.mutex+" "+prod_con.buffer); Thread.sleep(1000);}catch(Exception e){e.printStackTrace();} } prod_con.mutex=0; prod_con.buffer--; System.out.println("This is consumer "+this.name+" buffer is "+prod_con.buffer); prod_con.mutex=1; } }
Here there are four producers and two consumer threads. They check the buffer and their individual mutex. If the mutex is zero or the buffer is zero the consumers must wait. This is done via the sleep function. The producers too must take their turn along with the consumer to update the buffer value. OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PROGRAM 2: Simulating the Reader-Writer Problem Program: class readwr { static String res="$";static int mutex_r=1;static int read_count=0; static int mutex_w=1; public static void main(String args[]) {System.out.println("Begin"); new Thread(new reader("A")).start(); new Thread(new reader("B")).start(); new Thread(new writer("A")).start(); new Thread(new reader("E")).start(); new Thread(new writer("B")).start(); new Thread(new reader("C")).start(); new Thread(new reader("D")).start(); new Thread(new writer("C")).start(); System.out.println("End"); } } class reader implements Runnable {String name; reader(String n){name=n;} public void run() {while(readwr.mutex_r==0){try{System.out.println("Patiently waiting reader::"+name);Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}} readwr.mutex_r--; readwr.read_count++; if(readwr.read_count==1) {System.out.println("Reader "+name+" is first reader now"); readwr.mutex_w--; } readwr.mutex_r++; System.out.println("Reader "+name+" read the string::"+readwr.res); readwr.mutex_r--; System.out.println("Bye!! "+name); readwr.read_count--; if(readwr.read_count==0) {System.out.println("Last one "+name); readwr.mutex_w++; } readwr.mutex_r++; } } class writer implements Runnable {String name; Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
writer(String n){name=n;} public void run() { while(readwr.mutex_w==0){try{System.out.println("Patiently Waiting Writer:"+name);Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}} readwr.mutex_r--; System.out.println("The writer is ::"+name); readwr.mutex_w--; readwr.res+="$"; readwr.mutex_w++; System.out.println("I just wrote ::"+name+" this:"+readwr.res); readwr.mutex_r++; } }
In this program we use five reader threads and three writer threads. Here the reader threads can simultaneously read the shared variable. However they first restrict the writers from writing while they are reading. Once the writer get a chance it blocks the readers and other writers too, before it writes a data. Then it allows other writers to write. After all writers have written the readers are given a chance. Here we use the mutex and buffer as a static variable, so that it can be accessed by all classes.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
CONCLUSION: Thus we have simulated the reader writer problem and the producer consumer problem using java.
Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 11 AIM: To simulate the various page replacement techniques. THEORY: Page replacement is a common activity that the pager executes from time to time, especially in a demand paging environment which is prone to page faults and thus requires the pages to be swapped from the RAM and new pages be loaded. The three most commonly used algorithms are Least Recently Used, Optimal and First In First Out. In LRU the pages must have some mechanism to maintain the time since they were last referenced. Based on this the Least Recently used page must be replaced. Optimal must know in advance the page requests and according to the future requests the pages can be replaced. The page that is going to be referenced the latest is the one that is replaced. FIFO used simple First In First Out algorithm. Only a pointer is required to mark the first page and the algorithm has the working similar to that of a queue. PROGRAM: To simulate LRU/FIFO/OPTIMAL page replacement techniques. import java.util.Scanner; class page {public static void main(String args[]) {try{Scanner s=new Scanner(System.in); Spec buff[]= new Spec[3];int page_fault=0; for(int i=0;i<3;i++) buff[i]=new Spec(); int page2[]=new int[10]; for(int i=0;i<10;i++) {page2[i]=s.nextInt(); } /*for(int i=0;i<10;i++) {System.out.println(page[i]); }*/ System.out.println("Enter Algorithm used :: LRU/Optimal/FIFO"); String algo=s.next(); if(algo.equals("LRU")) {//System.out.println("Here"); int ptr=0;int n=0; System.out.print("Initial Buffer::");Spec.printb(buff,0); for(int i=0;i<10;i++) {//System.out.println("Here 2"); if(n<3) Operating Systems Lab, 2013-14
In this program the user inputs 10 page requests. The user then choses the algorithm and accordingly the program runs. For FIFO, a pointer a maintained to point to the first page. The pointer then moves in a circular fashion with every replacement. For LRU a special timer variable is used that increments with every iteration it is not referenced. A function then computes the least recently used page and replaces it. For Optimal, whenever a page must be replaced its closest reference is computed and accordingly the one which is going to be referenced after a long time is the one that will be replaced.
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
OUTPUT:
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
CONCLUSION: Thus we have simulated the various page replacement algorithms using Java.
Name of the Assessing Faculty: Professor Udmale Signature: _________________________ Dated: ________________
************
Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
PRACTICAL 12 AIM: To simulate the various scheduling algorithms. THEORY: Scheduling algorithms play a crucial role in the efficiency of the entire system. This is so because it is the schedulers job to utilize the CPU to its fullest, while also taking care that all the processes get a fair chance of executing. Various scheduling algorithms are used to schedule the processes. First Come Fist Serve, Round Robin, Shortest Job First and Shortest Remaining Time First are some algorithms that are implemented to schedule the processed. FCFS maintains a queue and executes a job to its full service time. Round Robin does maintain a queue but to ensure fairness uses discrete quanta, and after each quanta of time, it reschedules, putting the current process at the back of the queue and executing the next process. Shortest Job First computes the shortest job from the current lot of processed and executes it to its full service time. Shortest Remaining Time First used the similar concept but reschedules after a certain quanta where it checks the remaining time left of the various jobs and chooses the shortest one. PROGRAM: To simulate the various scheduling algorithms in java import java.util.Scanner; class Schedule { public static void main(String args[]) {int max_proc=5; Proc_Table pt[]=new Proc_Table[max_proc]; try{ Scanner s=new Scanner(System.in); System.out.println("Name"+" Ar_T "+"Ser_T"); for(int i=0;i<max_proc;i++) {String n=s.next(); int a=s.nextInt(); int se=s.nextInt(); //System.out.println(a+" "+se+" "+n ); pt[i]=new Proc_Table(n,a,se); //max_time+=se; } /*for(int i=0;i<max_proc;i++) Operating Systems Lab, 2013-14
if(pt[ptr].timer==pt[ptr].serv){count++; q=0;curr=0;cont=false;pt[ptr].used=true; } } Proc_Table.timechart(pt,i); } else{System.out.println("Algorithm not found pls enter from the list"); } } } } Operating Systems Lab, 2013-14
VJIT, Matunga, MUMBAI
}catch(Exception e){e.printStackTrace();} } } class Proc_Table { String name;boolean used; int arriv,serv,resp; int tim_arr[];int prev;int timer; Proc_Table(String n,int a,int s) {name=n;arriv=a;serv=s;prev=0; tim_arr=new int[40];used=false; for(int i=0;i<40;i++){tim_arr[i]=-1;} } static int search(String na,Proc_Table t[]) {int ind=0; for(int i=0;i<5;i++) {if((t[i].name).equals(na)) {ind=i; } } return ind; } static int search_short(Proc_Table t[],int time) {//System.out.println("0 is Index"); int index=100;int j=0; for(int i=0;i<5;i++) { if(!t[i].used && t[i].arriv<=time) {//System.out.println("Name::Is there and is not used"+t[i].name); if(t[i].serv < index) {//System.out.println("Name::Is smaller than the current index::"+t[i].name); j=i;index=t[i].serv; } } } return j; } static int search_short2(Proc_Table t[],int time) {//System.out.println("0 is Index"); int index=100;int j=0; for(int i=0;i<5;i++) {//System.out.println("Search::"+t[i].name+" "+t[i].used+" "+t[i].arriv+" "+time); if(!t[i].used && t[i].arriv<=time) {//System.out.println("Name::Is there and is not used "+t[i].name); if((t[i].serv-t[i].timer) < index) {//System.out.println("Name::Is smaller than the current index:: "+t[i].name); Operating Systems Lab, 2013-14