Operating System
Operating System
1. Is:
The ls command is commonly used to identify the files and directories in the working directory.
This command is one of the many often-used Linux commands that you should know.
$ls
2. pwd :
The pwd command is mostly used to print the current working directory on your terminal. It is
also one of the most commonly used commands.
$pwd
Output:
3. mkdir :
This mkdir command allows you to create fresh directories in the terminal itself. The default
syntax is mkdir <directory name> and the new directory will be created.
$mkdir mgmu
Output:
4. cd:
The cd command is used to navigate between directories. It requires either the full path or the
directory name, depending on your current working directory. If you run this command without
any options, it will take you to your home folder. Keep in mind that it can only be executed by
users with sudo privileges.
$pwd
$cd <directory name>
$pwd
Output:
5. rmdir:
The rmdir command is used to delete permanently an empty directory. To perform this command
the user running this command must be having sudo privileges in the parent directory.
$ls
$rmdir <directory name>
$ls
Output:
6. cp:
The cp command of Linux is equivalent to copy-paste and cut-paste in Windows.
$cp Src_file Dest_file
$gedit a.txt ( Insert some text in file and save)
$gedit b.txt (Leave bank and same file)
$cat a.txt (see content of a.txt)
$cat b.txt (no content in b.txt)
$cp a.txt b.txt (copy of a.txt to b.txt)
$cat a.txt (see content of a.txt)
$cat b.txt (see content of b.txt)
Output:
7. mv:
The mv command is generally used for renaming the files in Linux.
$mv [options(s)] [source_file_name(s)] [Destination_file_name]
Here,
source_file_name(s) = The name of the files that we want to rename or move.
Destination_file_name = The name of the new location or the name of the file.
$ls
$ touch first.txt ( To create file first.txt)
$mv first.txt renamed.txt
$ls
Output:
8. rm:
rm command in Linux is generally used to delete the files created in the directory.
$rm [OPTION]... FILE...
Let us consider 5 files having name a.txt, b.txt and so on till e.txt.
9. uname:
The uname command is used to check the complete OS information of the system.
uname [OPTIONs]
Options :
-a or --all : Displays all available information.
-s or --kernel-name : Shows the kernel name.
-n or --nodename : Displays the network (domain) name of the machine.
-r or --kernel-release : Shows the kernel release.
-v or --kernel-version : Displays the kernel version.
-m or --machine : Shows the machine hardware name.
-p or --processor : Displays the processor type or “unknown.”
-i or --hardware-platform :Shows the hardware platform or “unknown.”
-o or --operating-system: Displays the operating system.
$uname -a
$uname -s
$uname -n
$uname -r
$uname -v
$uname -m
$uname -p
Output:
10. locate:
The locate command is generally used to locate the files in the database. Use an asterisk (*) to
search for content that contains two or more words.
locate [OPTION]... PATTERN...
$locate "*.html" -n 20 (It will show 20 results for the searching of file ending with .html.)
$locate -c .txt (It will count files ending with .txt.)
$ locate -i *SAMPLE.txt* ( Ignore Case Sensitive Locate Outputs Using locate Command)
Output:
11. touch:
The touch command creates an empty file when put in the terminal in this format as touch <file
name>
touch [options] file_name
Options :
-a :This option changes the access time only.
-c : Suppresses file creation if the file does not exist.
-d : Sets the access and modification times using the specified STRING.
-m : This option changes the modification time only.
-r : Uses the access and modification times from the reference file.
$touch -a filename
$touch -c filename
$touch -c-d filename
Output:
12. ln:
The ln command is used to create a shortcut link to another file. This is among the most
important Linux commands to know if you want to operate as a Linux administrator.
$mkdir demo
$mkdir Linked
$ln -s demo Linked
Output:
13. cat:
The cat command is the simplest command to use when you want to see the contents of a
particular file. The only issue is that it simply unloads the entire file to your terminal. If you want
to navigate around a huge file, should use less command alternatively.
cat [OPTION] [FILE]
1. View the Content of a Single File in Linux : $cat file_name
2. View the Content of Multiple Files in Linux : $cat file_name1 file_name2
3. View Contents of a File preceding with Line Numbers in Linux : $cat -n file_name
4. Create a file and add content in Linux Using `cat` Command : $cat > newfile_name
5. Copy the Contents of One File to Another File in Linux : $cat file1.txt file2.txt >
merged_file.txt
Output:
14. clear:
The clear command is a standard command to clear the terminal screen
Clearing our terminal using `clear -x` in Linux System : $clear -x
Using `reset` command to clear our terminal in Linux System : $reset
Output:
15. ps:
ps command in Linux is used to check the active processes in the terminal.
ps [options]
Simple process selection : Shows the processes for the current shell : $ ps
To view all running processes, use either of the following options with the `ps` command: $ps -A
View all processes except both session leaders and processes not associated with a terminal : $ps
-a
A session leader is a process that initiates other processes. View processes except session
leaders: $ps -d
List All Processes Associated with this Terminal in Linux :$ps -
T Output:
16. man:
The man command displays a user manual for any commands or utilities available in the
Terminal, including their name, description, and options.
man [option] [command]
Options:
man [command]: Display the manual page for the specified command.
-f, –whatis: Display a concise one-line description of the command.
-k, –apropos: Search for commands related to a given keyword.
-a, –all: Display all matching manual pages for the specified command.
Spacebar: Move forward one page in the manual.
Enter: Move forward one line in the manual.
B: Move backward one page in the manual.
Q: Quit the manual viewer.
$man ls
$man 2 intro
$man -f ls
Output:
17. grep:
The grep command is used to find a specific string in a series of outputs. For example, if you
want to find a string in a file, you can use the syntax: <Any command with output> | grep
“<string to find> “
$cat Files.txt | grep “new”
Case insensitive search : $grep -i "UNix" mgmfile.txt
Displaying the Count of Number of Matches Using grep :$grep -c "unix" mgmfile.txt
Output:
18. echo:
echo command in Linux is specially used to print something in the terminal
$echo [string]
$echo "MGM University"
Output:
19. wget:
The wget command in the Linux command line allows you to download files from the internet. It
runs in the background and does not interfere with other processes.
Here is the basic syntax: $wget [option] [url]
$wget http://sample.com/sample-menu.php
Output:
20. whoami:
The whoami command provides basic information that is extremely useful when working on
multiple systems. In general, if you are working with a single computer, you will not require it as
frequently as a network administrator.
$whoami
$whoami --help
$whoami --version
$whoami -u
$whoami -e
Output:
21. sort :
The sort command is used generally to sort the output of the file. Let’s use the command and see
the output.
$cat multiple.txt
$sort multiple.txt
Here first we checked the file content using the cat command and then we sorted it alphabetically
using the sort command.
Output:
22. cal :
The cal command is not the most famous command in the terminal but it functions to view the
calendar for a particular month in the terminal. Let’s see how this works.
$cal [ [ month ] year]
$cal June 2024
$cal : Shows current month calendar on the terminal with the current date highlighted.
$cal -y : Shows the calendar of the complete current year with the current date highlighted.
$cal 08 2000 : Shows calendar of selected month and
year. 4cal 2018 : Shows the whole calendar of the year.
Output:
23. whereis:
whereis command in Linux is generally used to see the exact location of any command typed
after this. Let’s see how this performs.
$whereis [options] filename...
$whereis printf
Output:
24. df :
df command in Linux gets the details of the file system.
$df -h
Output:
25. wc :
wc command in Linux indicates the number of words, characters, lines, etc using a set of options.
wc -w shows the number of words
wc -l shows the number of lines
wc -m shows the number of characters present in a file
$touch file.txt
$echo -e "This file has only six words" > file.txt
$wc -w file.txt
Here we used the touch command to create a text file and then used the echo command to input a
sentence that contains six words and we used the wc -w command to calculate the number of
words in it.
Output:
Class- TY -03
Batch-C4
Roll no-4040
Practical: 04
Title : Basic of Shell programming
Shell is an interface of the operating system. It accepts commands from users and
interprets them to the operating system. If you want to run a bunch of commands
together, you can do so by creating a shell script.
Login to your Linux machine and open the terminal, navigate to the folder where
you want to store the shell script.Shell scripts end with the extension “.sh”. Let’s
create our first shell script. Type in
$touch script.sh
Now, this script file is not executable by default, we have to give the executable
permission to this file. Type in
$chmod +x script.sh
Now, we will add some commands to this shell script. Open this shell script with any
text editor of your choice (command-line based or GUI based) and add some
commands. We will use nano. Type in
$nano script.sh
$./script.sh
# This is a comment
echo Testing comments in shell script
Variables in Shell Script
There are two types of variables:
You can specify which shell the script will use, even if the script is executed from
another shell terminal. To do this, add “#!” on top of the script file, followed by the
absolute path of the shell of choice. To specify bash as an interpreter, Add the
following line on top of the shell script.
You can specify which shell the script will use, even if the script is executed from
another shell terminal. To do this, add “#!” on top of the script file, followed by the
absolute path of the shell of choice. To specify bash as an interpreter, Add the
following line on top of the shell script.
#!/bin/bash
Conditional statements
IF THAN :
#!/bin/sh
x=10
y=11
if [ $x -ne $y ]
then
echo "Not equal"
fi
IF THEN ELSE:
#!/bin/sh
x=10
y=10
if [ $x -ne $y ]
then
echo "Not equal"
else
echo "They are equal"
fi
Loops
Using loops, you can a set of commands over and over again, until a certain
#!/bin/sh
x=2
while [ $x -lt 6 ]
do
echo $x
x=`expr $x + 1`
done
FOR LOOP :
#!/bin/sh
for var in 2 4 5 8
do
echo $var
done
Positional Arguments
Positional arguments are the arguments or values which we pass to the shell script
while executing the script. They are accessed by variables $0, $1, $2 … $9. Beyond
that, they are referenced by ${10}, ${11} and so on. $# stores the no of passed
arguments and $0 stores the name of the script. Let’s see an example to
understand all this.
bin/sh
eco "No of arguments is $#"
echo "Name of the script is $0"
echo "First argu#!/ment is $1"
echo "Second argument is $2"h
Syntax
#Syntax 1
var=$(a valid linux command)
#Syntax 2
var2=`a valid linux
example.
#!/bin/sh
b=$(pwd)
c=`pwd`
echo $b
echo $c
d=$(ls /bin | grep bash)
echo $d
You can manually set an exit code for your shell script. This can be used with
conditional statements to convey if the script’s purpose was achieved or not.
Example
#!/bin/sh
read x
if [ $x -ne 10 ]
then
echo failed
exit 1
else
echo passed
exit 0
fi
Class-TY -03
Batch-CSE
Roll no-4040
Practical-5
Title : Shell Script programming using grep, awk, sed
/home/cse40/lab5
|-- file1.txt
|-- file2.txt
|-- lab5subdir
|-- file3.txt
Now, if you want to search for the word "Hello" in the `/lab5`, you can use
the script as follows:
$touch grep_script.sh
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <pattern> <directory>"
exit 1
fi
pattern=$1
directory=$2
# Search for the pattern in the specified directory and its subdirectories
grep -r "$pattern" "$directory"
Expected Output:
/home/cse40/lab5/file1.txt:Hello world
/home/cse40/lab5/lab5subdir/file3.txt:Hello again
This output shows the lines containing the word "Hello" along with the file
names where the pattern was found.
Shell Script programming using awk :
Here is a simple `awk` script example to extract and print specific columns from
a file:
$touch awk_script.sh
$nano awk_script.sh
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <column1> <column2> <file>"
exit 1
fi
column1=$1
column2=$2
file=$3
# Use awk to print the specified columns
awk -v col1="$column1" -v col2="$column2" '{print $col1, $col2}' "$file"
If you want to extract and print the first and third columns (ID and age), you
can use the script as follows:
Expected Output:
1 25
2 30
3 22
4 28
This output shows the first and third columns of each line from the `data.txt` file.
Shell Script programming using sed :
SED command in UNIX stands for stream editor and it can perform lots of functions on file like
searching, find and replace, insertion or deletion. Though most common use of SED command in
UNIX is for substitution or for find and replace. By using SED you can edit files even without
opening them, which is much quicker way to find and replace something in file, than first
opening that file in VI Editor and then changing it.
● SED is a powerful text stream editor. Can do insertion, deletion, search and
replace(substitution).
● SED command in unix supports regular expression which allows it perform complex
pattern matching.
$touch awk_script.sh
$nano awk_script.sh
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <pattern> <replacement> <file>"
exit 1
fi
pattern=$1
replacement=$2
file=$3
# Use sed to replace the pattern with the replacement string in the specified file
sed -i "s/$pattern/$replacement/g" "$file"
If you want to replace the word "Hello" with "Hi", you can use the script as
follows:
Hi world
This is a
test Hi
again
This script replaces all occurrences of the word "Hello" with "Hi" in the
`example.txt` file.
Conclusion : hence we studied about the shell programming using sed awk and
grep
Output
Practical-o6
Title : Demonstration of fork, execve and wait system calls
Save
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process (PID: %d)\n", getpid());
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
} else {
printf("Child did not exit successfully\n");
}
}
return 0;
}
Explanation:
1. Forking:
- `pid = fork();` creates a new process. The new process is the child process, which is a copy of the
parent process. The return value of `fork` is zero in the child process and the child's PID in the parent
process.
Expected Output
When you compile and run this program, the output should look something like this:
Explanation:
1. Parent process (PID: 3015):- This line is printed by the parent process immediately after the `fork`
system call.
2. Child process (PID: 3016): This line is printed by the child process immediately after the `fork` system
call.
3. Output of `ls -l` command: The child process executes the `ls -l` command, listing the directory
contents in long format. The exact output will depend on the contents of the directory where the program
is run.
4. Child exited with status 0: This line is printed by the parent process after the child process has finished
executing and terminated with an exit status of 0, indicating successful execution.
Conclusion : Hence we studied about of fork, execve and wait system calls
Output -
Practical 07
Title : Inter-process Communication (IPC) in Linux
=======================================================================
Inter-process Communication (IPC) in Linux is crucial for allowing processes to communicate with each
other.
Communication pipe_example.c
#include <stdio.h> // For printf and perror
#include <unistd.h> // For pipe, fork, read, write, and
close #include <string.h> // For strlen
int main() {
int fd[2]; // Array to hold the file descriptors for the pipe
pid_t pid; // Variable to hold the process ID
char write_msg[] = "Hello, world!"; // Message to be written to the pipe
char read_msg[20]; // Buffer to hold the message read from the pipe
// Create a pipe
if (pipe(fd) == -1) {
perror("pipe"); // Print an error message if pipe creation fails
return 1; // Exit with a non-zero status to indicate an
error
}
`
Compilation and Execution:
$gcc -o pipe_example pipe_example.c
$./pipe_example
Expected Output:
Parent read: Hello, world!
Messages msg_queue_example.c
#include <stdio.h> // For printf and perror
#include <stdlib.h> // For exit()
#include <sys/ipc.h> // For ftok() and key_t
#include <sys/msg.h> // For msgget(), msgsnd(), msgrcv(),
msgctl() #include <string.h> // For strcpy()
int main() {
key_t key; // Variable to hold the IPC key
int msgid; // Variable to hold the message queue ID
Expected Output:
Sent message: Hello, world!
Received message: Hello, world!
3. Shared Memory : Writing and Reading Shared
Memory shm_example.c
int main() {
// Generate a unique key for the shared memory segment
key_t key = ftok("shmfile", 65); // "shmfile" is a file used to generate the key; 65 is a project-specific
identifier
// Detach the shared memory segment from the process's address space
shmdt(str); // Detach the shared memory segment
Expected Output:
Data written in memory: Hello, world!
`
Conclusion: practical implementations of various IPC mechanisms in Linux. You can build more
complex applications by combining these techniques as needed.
Practical 08
Title : Linux Commands for System Administrators
Linux System Administrator involves the installation, configuration, maintenance and management
of Linux-based systems.
1. Uptime Command
The Linux uptime command shows how long your system is running and the number of users who are
currently logged in and also displays the load average of a system for 1, 5, and 15 minutes intervals.
# uptime
08:16:26 up 22 min, 1 user, load average: 0.00, 0.03, 0.22
Uptime command don’t have other options other than uptime and version. It gives information
only in hours:mins:sec if it is less than 1 day.
# uptime -V
procps version 3.2.8
2. W Command
The w command will display users currently logged in and their process along with showing load
averages, login name, tty name, remote host, login time, idle time, JCPU, PCPU, command, and
processes.
#w
08:27:44 up 34 min, 1 user, load average: 0.00, 0.00, 0.08 TTYFROM USER
LOGIN@ IDLE JCPU PCPU WHAT tecmint pts/0
192.168.50.1 07:590.00s 0.29s 0.09s w
● Available Options
● -h : displays no header entries.
● -s : without JCPU and PCPU.
● -f : Removes from the field.
● -V : (upper letter) – Shows versions.
3. Users Command
Users command displays currently logged-in users. This command doesn’t have other parameters other
than help and version.
# users
tecmint
4. Who Command
Who command returns the user name, date, time, and host information. who command is similar to w
command. Unlike the w command who doesn’t print what users are doing. Let’s illustrate and see the
difference between who and w commands.
# who
tecmint pts/0 2012-09-18 07:59 (192.168.50.1)
#w
08:43:58 up 50 min, 1 user, load average: 0.64, 0.18, 0.06 USERTTYFROM
LOGIN@ IDLE JCPU PCPU WHAT
tecmint pts/0192.168.50.1 07:590.00s 0.43s 0.10s w
5. ls Command
# ls -l
total 114
dr-xr-xr-x. 2 root root 4096 Sep 18 08:46 bin
dr-xr-xr-x. 5 root root 1024 Sep 8 15:49 boot
Sort file as per last modified time.
# ls -ltr
total 40
-rw-r--r--. 1 root root 6546 Sep 17 18:42 install.log.syslog
-rw-r--r--. 1 root root 22435 Sep 17 18:45 install.log
-rw-------. 1 root root 1003 Sep 17 18:45 anaconda-ks.cfg
6. Crontab Command
List scheduled jobs for current users with crontab command and -l option.
# crontab -l
00 10 * * * /bin/ls >/ls.txt
Edit your crontab with -e the option. The below example will open scheduled jobs in VI
editor. Make necessary changes and quit pressing :wq keys that save the setting
automatically.
# crontab -e
7. Less Command
less command allows quickly viewing the file. You can page up and down. Press ‘q‘
to quit from less window.
# less install.log
Installing setup-2.8.14-10.el6.noarch
warning: setup-2.8.14-10.el6.noarch: Header V3 RSA/SHA256 Signature, key ID
c105b9de: NOKEY
Installing filesystem-2.4.30-2.1.el6.i686
Installing ca-certificates-2010.63-
3.el6.noarch Installing xml-common-
0.6.3-32.el6.noarch Installing tzdata-
2010l-1.el6.noarch
Installing iso-codes-3.16-2.el6.noarch
8. More Command
more command allows quickly view file and shows details in percentage. You can
page up and down. Press ‘q‘ to quit out from more window.
# more install.log
Installing setup-2.8.14-10.el6.noarch
warning: setup-2.8.14-10.el6.noarch: Header V3 RSA/SHA256 Signature, key ID
c105b9de: NOKEY
Installing filesystem-2.4.30-2.1.el6.i686
Installing ca-certificates-2010.63-
3.el6.noarch Installing xml-common-
0.6.3-32.el6.noarch
Installing tzdata-2010l-1.el6.noarch
Installing iso-codes-3.16-2.el6.noarch
--More--(10%)
SSH command is used to login into the remote host. For example, the below ssh
command will connect to the remote host (192.168.50.2) using the user as Narad.
# ssh
[email protected]
10. ps command
The ps command displays processes running in the system. The below example show the
init
to process only.
# kill- 9 7508
Conclusion: successfully executed command for Linux Commands for System Administrator
Practical: 09
Title : Implementation of CPU scheduling using the FCFS Algorithm, SJF Algorithm, and
Round Robin Algorithm, Priority Algorithm
—
Implementing CPU scheduling algorithms like FCFS (First-Come, First-Served), SJF (Shortest Job First), Round Robin,
and Priority Scheduling can be a great way to understand how operating systems manage process execution.
Function FCFS_Scheduling(processes):
processes
Set total_turnaround_time to
0 Sort processes by
arrival_time
if i is 1:
zero waiting_time[i] = 0
else # Calculate waiting time as the sum of burst times of all previous
turnaround_time[i] = waiting_time[i] +
waiting_time[i]The FCFS
total_turnaround_time +=
turnaround_time[i]
The SJF algorithm selects the process with the shortest burst time from the ready queue. It can be either
preemptive or non-preemptive.
Function SJF_Scheduling(processes):
Set total_turnaround_time to
0 Sort processes by
burst_time
if i is 1:
zero waiting_time[i] = 0
else:
turnaround_time[i] = waiting_time[i] +
waiting_time[i] total_turnaround_time +=
turnaround_time[i]
processes
while True:
done = Trueand cycles through them until all processes are complete.
if remaining_time[i] > 0:
done = False
remaining_time[i] -=
time_quantum else:
quantum time +=
remaining_time[i] waiting_time[i]
= time - burst_time[i]
remaining_time[i] = 0
if done:
break
turnaround_time[i] = waiting_time[i] +
Function Priority_Scheduling(processes):
# processes is a list of tuples (process_id, burst_time, priority)
// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
findavgTime(processes, n, burst_time);
return 0;
}
Output-