0% found this document useful (0 votes)
24 views55 pages

Linux Lab

The document is a practical manual for the course U23ADB401 - Linux Internals, designed for B.Tech students in the Artificial Intelligence and Data Science department. It covers essential Linux concepts, shell programming, inter-process communication, and socket programming, along with laboratory exercises for hands-on practice. The manual outlines course outcomes, unit topics, and various Linux commands, providing a comprehensive guide for students to learn and apply Linux internals effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views55 pages

Linux Lab

The document is a practical manual for the course U23ADB401 - Linux Internals, designed for B.Tech students in the Artificial Intelligence and Data Science department. It covers essential Linux concepts, shell programming, inter-process communication, and socket programming, along with laboratory exercises for hands-on practice. The manual outlines course outcomes, unit topics, and various Linux commands, providing a comprehensive guide for students to learn and apply Linux internals effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

DEPARTMENT OF

A R T I F I CI A L I N T E L L I G E N C
E AND
D A T A S C I E N CE

U23ADB401 - Linux Internals

PRACTICAL MANUAL

Year/Semester/Sec:

II/IV/A&B Regulation : R-23

Prepared By Verified By Approved By

Dr. J. Madhusudanan

1
Department Artificial Intelligence and Data Programme: B.Tech.
Science
Semester IV Course Category: ES End Semester Exam Type:
TE
Periods Credit Maximum Marks
Course Code U23ADB401 / Week
L T P C CAM ESE
Course Name Linux Internals 2 - 2 3 50 50
(Common to all Branches)
Prerequisite Any Programming Knowledge
On completion of the course, the students will be able to

Course CO1 Understand concepts of OS basics


Outcome CO2 Learn various Linux basics and shell programming
s CO3 Learn about inter process communication and socket
programming
CO4 Apply various Linux commands and shell programming concepts
CO5 Apply IPC concepts, message queue and socket programming
concepts
Overview of Operating Systems and Process
UNIT-I Periods: 10
Management
Introduction to System Software – Objectives and functions of OS – Evolution of OS – Operating
system components – Interrupts – System calls, Management: Processes – Operations on Processes –
CPU Scheduling. Threads – Overview – Multithreading models – Threading issues - Paging –
Segmentation – Segmentation with paging, Virtual Memory: Background – Demand Paging – Page
Replacement – Thrashing.
UNIT-II Linux Basics and Shell Programming Periods: 10
Linux Basics: Introduction to Linux: History, GNU Movement, System Organization (Kernel and Shell),
Difference between CLI OS & GUI OS, Windows v/s Linux, Importance of Linux Kernel, Files and
Directories. Concept of Open- Source Software, Linux, Linux Architecture, Linux File System. Shell
programming with Bourne Again Shell (bash): Introduction, Shell responsibilities, Pipes and
redirection, here documents, Running a shell script, Shell as a
programming language, Shell meta characters, File-name substitution, Shell variables, Command.
substitution, Shell commands.
UNIT-III Inter Process Communication, and Socket Periods: 10
Programming
Introduction to IPC-The Critical-section problem – Synchronization hardware – Mutex locks –
Semaphores – Classic problems of synchronization – Critical regions – Monitors, IPC between
processes on a single computer system, IPC between processes on different systems, Pipes-creation
between related processes using FIFOs (Named pipes), Introduction to Berkley Sockets, IPC over a
network, client – server model, Socket address structures (Unix domain and internet domain),
Socket system calls for connection-oriented protocol and connectionless protocol
UNIT-IV Laboratory Exercises Periods: 15
 Study and Practice on various commands like man, passwd, tty, script, clear,
date, cal, cp, mv, ln, rm, unlink, mkdir, rmdir, du, df, mount, umount, find,
unmask, ulimit, ps, who,
 Study and Practice on various commands like cat, tail, head , sort, nl, uniq, grep,
egrep,fgrep, cut, paste, join, tee, pg, comm, cmp, diff, tr, awk, tar, cpio.
 Write a Shell Program to print all .txt files and .c files
 Write a Shell program to move a set of files to a specified directory.
 Write a Shell program to display all the users who are currently logged in after a
specified time.
 Write a Shell Program to wish the user based on the login time.
 Simulate cat command. b) Simulate cp command.
 Simulate head command. b) Simulate tail command.
UNIT-V Laboratory Exercises Periods: 15
 Write a program to handle the signals like SIGINT, SIGQUIT, SIGFPE.
 Implement the following IPC forms a) FIFO b) PIPE
 Implement message queue form of IPC.

2
 Implement shared memory form of IPC.
 Write a C program, using sockets create client and server socket programs. Write
a TCP iterative server program, in server program take user input for port number
and bind the port address. Server waits for
 clients to connect. When client connects, communication can happen using recv
and sent functions.

TABLE OF CONTENTS

EX.NO DATE TITLE OF THE EXERCISE PAGE NO

1 Various Linux system and file management


commands
2 Various Linux commands for file manipulation,
text processing, and data archiving

3 Shell script that prints the names of all .txt


and .c files
4 shell script to move a set of files

5 Shell script that displays all the users

6 Shell script that wishes the user based on the


login time

7 Shell programs to simulate the functionality of


the cat and cp commands

Simulate the functionality of the head and tail


8
commands

3
TABLE OF CONTENTS

EX.NO DATE TITLE OF THE EXERCISE PAGE NO

9 Handles the signals SIGINT, SIGQUIT, and


SIGFPE in C
10
IPC mechanisms using FIFO and PIPE

11 Inter-Process Communication (IPC) using the


shared memory mechanism

12 TCP iterative server and client socket program

13 TCP iterative server-client program

4
UNIT - IV

5
EX.NO: Various Linux system and file management
DATE : commands

AIM

To learn and understand the usage of various Linux system and file management commands such as man,
passwd, tty, script,etc.

PROCEDURE

 Set up a Linux environment using a virtual machine, WSL, or a live Linux distribution.
 Open the terminal and execute each command with different options to explore its behavior.
 Use the manual (man) command to understand the options available for each command.
 Record the commands and their outputs to analyze the results.

PROGRAM

1) man

o Usage: Display manual pages for a command.


o Command: man ls
o Output: Displays the manual for the ls command with details about usage and options.

2) passwd

o Usage: Change the user password.


o Command: passwd
o Output: Prompts for the current password and then allows setting a new password.

3) tty

o Usage: Print the name of the terminal connected.


o Command: tty
o Output: /dev/pts/0 (or similar depending on the terminal session).

4) script

o Usage: Record the terminal session to a file.


o Command: script session.log
o Output: Starts recording the terminal session in session.log. Type exit to stop recording.

5) clear

o Usage: Clear the terminal screen.


o Command: clear
o Output: Clears the terminal screen.

6
6) date

o Usage: Display or set the system date and time.


o Command: date
o Output: Wed Dec 20 11:15:00 IST 2024

7) cal

 Usage: Display a calendar.


 Command: cal
 Output: Displays the calendar for the current month.

8) cp

 Usage: Copy files or directories.


 Command: cp file1.txt file2.txt
 Output: Copies file1.txt to file2.txt.

9) mv

 Usage: Move or rename files.


 Command: mv file1.txt newfile.txt
 Output: Renames or moves file1.txt to newfile.txt.

10) ln

 Usage: Create hard or symbolic links to files.


 Command: ln -s file1.txt link1.txt
 Output: Creates a symbolic link link1.txt pointing to file1.txt.

11) rm

 Usage: Remove files.


 Command: rm file2.txt
 Output: Deletes file2.txt.

12) unlink

 Usage: Remove a single file.


 Command: unlink file2.txt
 Output: Deletes file2.txt.

13) mkdir

 Usage: Create directories.


 Command: mkdir mydir
 Output: Creates a directory named mydir.

14) rmdir

7
 Usage: Remove empty directories.
 Command: rmdir mydir
 Output: Deletes the mydir directory if it is empty.

15) du

 Usage: Estimate disk usage of files and directories.


 Command: du -h file1.txt
 Output: Displays the disk usage of file1.txt in human-readable format.

16) df

 Usage: Report filesystem disk space usage.


 Command: df -h
 Output: Filesystem Size Used Avail Use% Mounted on /dev/sda1 50G 20G 30G
40% /

17) mount

 Usage: Mount a filesystem.


 Command: mount /dev/sdb1 /mnt
 Output: Mounts the device /dev/sdb1 to /mnt.

18) umount

 Usage: Unmount a filesystem.


 Command: umount /mnt
 Output: Unmounts the filesystem at /mnt.

19) find

 Usage: Search for files and directories.


 Command: find / -name "file1.txt"
 Output: Displays the full path of file1.txt if it exists.

20) umask

 Usage: Display or set default file permissions.


 Command: umask 022
 Output: Sets the default file permission mask to 022.

21) ulimit

 Usage: Display or set user process resource limits.


 Command: ulimit -n
 Output: Displays the maximum number of open file descriptors.

22)
8
 Usage: Display process status.
 Command: ps
 Output: Lists currently running processes with details like PID and TTY.

23) who

 Usage: Show logged-in users.


 Command: who
 Output: Displays a list of logged-in users, their terminal, and login time.

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

9
EX.NO: Various Linux commands for file
DATE: manipulation, text processing, and data
archiving

AIM:

To study and practice various Linux commands for file manipulation, text processing, and data archiving,
such as cat, tail, head, sort, nl, uniq, grep, awk, tar, and others.

PROCEDURE

1. Set up a Linux environment using a virtual machine, WSL, or a live Linux distribution.
2. Open the terminal and execute each command individually with relevant files to explore its functionality.
3. Use the man command to read the manual and understand the available options for each command.
4. Create sample text files to experiment with file management and text processing commands.
5. Use multiple options for each command to analyze and understand their variations.
6. Record the commands, their usage, and the output generated for each operation.
7. For commands like tar and cpio, create multiple files to experiment with archiving and compression
functionalities.

PROGRAM:

1) cat

 Usage: Concatenate and display file content.


 Command: cat file1.txt
 Output: Displays the content of file1.txt.

2) tail

 Usage: Display the last few lines of a file.


 Command: tail -n 5 file1.txt
 Output: Displays the last 5 lines of file1.txt.

3) head

 Usage: Display the first few lines of a file.


 Command: head -n 5 file1.txt
 Output: Displays the first 5 lines of file1.txt.

4) sort

 Usage: Sort the lines in a file.


 Command: sort file1.txt
 Output: Displays the sorted content of file1.txt.

10
5) nl

 Usage: Number the lines in a file.


 Command: nl file1.txt
 Output: Displays file1.txt with line numbers.

6) uniq

 Usage: Filter out duplicate lines in a file.


 Command: uniq file1.txt
 Output: Displays unique lines from file1.txt.

7) grep

 Usage: Search for a pattern in a file.


 Command: grep "hello" file1.txt
 Output: Displays lines containing "hello" in file1.txt.

8) egrep

 Usage: Search for a pattern using extended regular expressions.


 Command: egrep "hello|world" file1.txt
 Output: Displays lines containing "hello" or "world" in file1.txt.

9) fgrep

 Usage: Search for fixed strings in a file.


 Command: fgrep "hello" file1.txt
 Output: Displays lines containing the exact string "hello" in file1.txt.

10) cut

 Usage: Extract specific fields or columns from a file.


 Command: cut -d',' -f2 file1.csv
 Output: Displays the second column of file1.csv using ',' as the delimiter.

11) paste

 Usage: Merge lines from multiple files.


 Command: paste file1.txt file2.txt
 Output: Merges lines from file1.txt and file2.txt side by side.

12) join

 Usage: Join lines from two files on a common field.


 Command: join file1.txt file2.txt
 Output: Joins matching lines from file1.txt and file2.txt.

11
13) tee

 Usage: Redirect output to a file and display it.


 Command: ls | tee output.txt
 Output: Displays the output of ls and saves it to output.txt.

14) pg

 Usage: View files one screen at a time.


 Command: pg file1.txt
 Output: Displays file1.txt one screen at a time.

15) comm

 Usage: Compare two sorted files line by line.


 Command: comm file1.txt file2.txt
 Output: Displays lines unique to each file and common lines.

16) cmp

 Usage: Compare two files byte by byte.


 Command: cmp file1.txt file2.txt
 Output: Displays the first difference between file1.txt and file2.txt.

17) diff

 Usage: Compare two files line by line.


 Command: diff file1.txt file2.txt
 Output: Displays line-by-line differences between file1.txt and file2.txt.

18) tr

 Usage: Translate or delete characters.


 Command: tr 'a-z' 'A-Z' < file1.txt
 Output: Converts lowercase letters in file1.txt to uppercase.

19) awk

 Usage: Pattern scanning and processing.


 Command: awk '{print $1}' file1.txt
 Output: Displays the first column of file1.txt.

20) tar

 Usage: Archive files.


 Command: tar -cvf archive.tar file1.txt file2.txt
 Output: Creates an archive archive.tar containing file1.txt and file2.txt.

21) cpio

 Usage: Copy files to/from an archive.


 Command: ls | cpio -ov > archive.cpio
12
 Output: Creates an archive archive.cpio with the files listed by ls.

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

13
EX.NO: Shell script that prints the names of all
DATE: .txt and .c files

AIM:
To write a shell script that prints the names of all .txt and .c files in the current
directory.

PROCEDURE

1. Set up a Linux environment with a terminal.


2. Open a text editor such as vi, nano, or any other editor to write the shell script.
3. Use commands like ls and grep to filter files with .txt and .c extensions.
4. Save the script with a .sh extension and make it executable using the chmod command.
5. Execute the script to display all .xt and .c files in the current directory.

PROGRAM:

#!/bin/bash

# Shell script to list all .txt and .c files

echo"Listing all .txt files:"

ls *.txt 2>/dev/null

echo "Listing all .c files:" ls *.c 2>/dev/null

INPUT:

Assuming the current directory contains the following files:

 file1.txt
 file2.txt
 program.c
 example.c

When you execute the script:

$ ./list_files.sh

14
OUTPUT:
Listing all .txt files:
file1.txt
file2.txt
Listing all .c files:
program.c
example.c

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

15
EX.NO: shell script to move a set of files
DATE:

AIM:

To write a shell script to move a set of files to a specified directory.

PROCEDURE

1. Set up a Linux environment and open a terminal.


2. Create the shell script using a text editor like nano or vi.
3. Use the mv command in the script to move files from the current directory to the specified directory.
4. Accept file names and the target directory as input from the user.
5. Save the script with a .sh extension and make it executable using the chmod command.

PROGRAM:
#!/bin/bash
# Shell script to move a set of files to a specified directory
echo "Enter the names of the files to move (separated by space):"
read -a files

echo "Enter the destination directory:"


read dest_dir

# Check if the destination directory exists


if [ -d "$dest_dir" ]; then
# Loop through each file and move it to the destination
for file in "${files[@]}"; do
if [ -f "$file" ]; then
mv "$file" "$dest_dir"
echo "Moved $file to $dest_dir"
else
echo "File $file does not exist."
fi
done
else
echo "Directory $dest_dir does not exist."
fi

16
OUTPUT:

Assume the current directory contains file1.txt and file2.txt, and the destination directory is
/home/user/documents.

1) Moving files successfully

$ ./move_files.sh

Enter the names of the files to move (separated by space):

file1.txt file2.txt

Enter the destination directory:

/home/user/documents

Moved file1.txt to /home/user/documents

Moved file2.txt to /home/user/documents

2) Non-existent file:

$ ./move_files.sh

Enter the names of the files to move (separated by space):

file3.txt

Enter the destination directory:

/home/user/documents

File file3.txt does not exist.

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

17
EX.NO:
DATE:
Shell script that displays all the users

AIM:

To write a shell script that displays all the users who are currently logged in after a specified time.

PROCEDURE

1. Set up a Linux environment and open a terminal.


2. Open a text editor (e.g., nano, vi) to write the shell script.
3. Use the who command to get the list of currently logged-in users.
4. Use the sleep command to wait for the specified amount of time before displaying the logged-in users.
5. Save the script with a .sh extension and make it executable using the chmod command.
6. Execute the script and specify the desired time after which the logged-in users will be displayed.

PROGRAM:

#!/bin/bash

# Shell script to display all the users who are currently logged in after a specified time

# Ask for the time delay in seconds

echo "Enter the time (in seconds) after which you want to display the logged-in users:"

read delay_time

# Wait for the specified time

sleep $delay_time

# Display the list of users who are currently logged in

echo "Users currently logged in after $delay_time seconds:"

who

18
OUTPUT:

Example 1: After waiting for a specified time (e.g., 10 seconds)

$ ./logged_in_users.sh

Enter the time (in seconds) after which you want to display the logged-in users:

10

[After waiting for 10 seconds]

Users currently logged in after 10 seconds:

user1 tty1 2024-12-20 09:00 (:0)

user2 pts/1 2024-12-20 09:15 (:0)

user3 pts/2 2024-12-20 09:20 (:0)

Example 2: If no users are logged in at the time

$ ./logged_in_users.sh

Enter the time (in seconds) after which you want to display the logged-in users:

[After waiting for 5 seconds]

Users currently logged in after 5 seconds:

(no output, as no users are logged in)

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

19
EX.NO:
DATE:
Shell script that wishes the user
based on the login time

AIM:

To write a shell script that wishes the user based on the login time (Good Morning, Good Afternoon, or Good
Evening).

PROCEDURE:

1. Set up a Linux environment and open a terminal.


2. Open a text editor (e.g., nano, vi) to write the shell script.
3. Use the date command to get the current time.
4. Depending on the time of day (morning, afternoon, or evening), the script will display a different greeting.
5. Save the script with a .sh extension and make it executable using the chmod command.
6. Execute the script to see the greeting based on the current time.

PROGRAM:

#!/bin/bash

# Shell script to wish the user based on the login time

# Get the current hour using the date command

current_hour=$(date +%H)

# Determine the time of day and display an appropriate greeting

if [ $current_hour -ge 0 ] && [ $current_hour -lt 12 ]; then

echo "Good Morning, $(whoami)!"

elif [ $current_hour -ge 12 ] && [ $current_hour -lt 18 ]; then

echo "Good Afternoon, $(whoami)!"

else

echo "Good Evening, $(whoami)!"

fi

20
OUTPUT

Example 1: If the time is in the morning (e.g., 9:00 AM):

$ ./wish_user.sh
Good Morning, user!

Example 2: If the time is in the afternoon (e.g., 2:00 PM)


$ ./wish_user.sh
Good Afternoon, user!

TERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

21
EX.NO:
DATE: Shell programs to simulate the functionality of the
cat and cp commands
AIM

To write shell programs to simulate the functionality of the cat and cp commands.

PROCEDURE

1. Set up a Linux environment and open a terminal.


2. Open a text editor (e.g., nano, vi) to write the shell scripts.
3. For simulating cat:

--> Open the file and display its contents on the terminal.

4. For simulating cp:

--> Copy the contents of a source file to a destination file.

5. Save the scripts with .sh extensions and make them executable using the chmod command.
6. Execute the scripts to simulate the cat and cp commands.

PROGRAM:

1) Simulate cat Command

#!/bin/bash

# Shell script to simulate the cat command

# Check if a file name is provided

if [ $# -ne 1 ]; then

echo "Usage: $0 <filename>"

exit 1

fi

# Check if the file exists

if [ ! -f $1 ]; then
22
echo "File not found!"

exit

fi

# Display the contents of the file

cat $1

2) Simulate cp Command:

#!/bin/bash

# Shell script to simulate the cp command

# Check if source and destination files are provided

if [ $# -ne 2 ]; then

echo "Usage: $0 <source_file> <destination_file>"

exit 1

fi

# Check if the source file exists

if [ ! -f $1 ]; then

echo "Source file not found!"

exit 1

fi

# Copy the contents of the source file to the destination file

cp $1 $2

echo "File copied from $1 to $2"

23
OUTPUT:

For Simulating cat Command

1) Display contents of a file:

$ ./simulate_cat.sh testfile.txt

Hello, this is a test file.

2) If the file does not exist:

$ ./simulate_cat.sh non_existent_file.txt

File not found!

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

24
EX.NO:
DATE:
Simulate the functionality of the head and tail
commands
AIM:

To write shell programs that simulate the functionality of the head and tail commands.

PROCEDURE:

1. Set up a Linux environment and open a terminal.


2. Open a text editor (e.g., nano, vi) to write the shell scripts.
3. For simulating head:
1. Display the first 10 lines of a file by default or a specified number of lines.
4. For simulating tail:

1. Display the last 10 lines of a file by default or a specified number of lines.

5. Save the scripts with .sh extensions and make them executable using the chmod command.
6. Execute the scripts to simulate the head and tail commands.

PROGRAM:

1) Simulate head Command:

#!/bin/bash

# Shell script to simulate the head command

# Check if a file name is provided

if [ $# -ne 1 ]; then

echo "Usage: $0 <filename>"

exit 1

fi

# Check if the file exists

25
if [ ! -f $1 ]; then

echo "File not found!"

exit 1

fi

# Display the first 10 lines of the file by default

head -n 10 $1

2) Simulate tail Command:

#!/bin/bash

# Shell script to simulate the tail command

# Check if a file name is provided

if [ $# -ne 1 ]; then

echo "Usage: $0 <filename>"

exit 1

fi

# Check if the file exists

if [ ! -f $1 ]; then

echo "File not found!"

exit 1

fi

# Display the last 10 lines of the file by default

tail -n 10 $1

26
CRITERIA MAX.MARKS MARKS OBTAINED
AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

27
Unit

UNIT V

28
EX.NO: Handles the signals SIGINT, SIGQUIT, and
DATE:
SIGFPE in C

AIM:

To write a program that handles the signals SIGINT, SIGQUIT, and SIGFPE.

PROCEDURE:

1. Set up a Linux environment with a C compiler (e.g., gcc).


2. Open a text editor and write a program to define signal handlers for the following signals:
1. SIGINT: Triggered by pressing Ctrl+C.
2. SIGQUIT: Triggered by pressing Ctrl+\.
3. SIGFPE: Triggered by a floating-point exception, e.g., division by zero.
3. Use the signal() function to link each signal with its corresponding handler.
4. Compile and run the program.
5. Trigger each signal during program execution to verify the custom handlers.

PROGRAM:

#include <stdio.h>

#include <signal.h>

#include <stdlib.h>

// Handler for SIGINT (Ctrl+C)

void handle_sigint(int sig) {

printf("Caught signal SIGINT (Ctrl+C). Exiting gracefully.\n");

exit(0);

// Handler for SIGQUIT (Ctrl+\)

void handle_sigquit(int sig) {

printf("Caught signal SIGQUIT (Ctrl+\\). Cleaning up and exiting.\n");

exit(0);
29
}

// Handler for SIGFPE (Floating-point exception)

void handle_sigfpe(int sig) {

printf("Caught signal SIGFPE (Division by zero). Avoid illegal operations.\n");

exit(0);

int main() {

// Register signal handlers

signal(SIGINT, handle_sigint);

signal(SIGQUIT, handle_sigquit);

signal(SIGFPE, handle_sigfpe);

printf("Signal handler program is running.\n");

printf("Press Ctrl+C (SIGINT) or Ctrl+\\ (SIGQUIT) to trigger signals.\n");

printf("Or perform a division by zero to trigger SIGFPE.\n");

// Simulate division by zero to test SIGFPE

int x = 0;

printf("Performing a division by zero...\n");

int result = 10 / x; // This will trigger SIGFPE

return 0;

OUTPUT:

Case 1: Trigger SIGINT (Ctrl+C):

$ ./signal_handler
30
Program started. Waiting for signals.

Press Ctrl+C to trigger SIGINT or Ctrl+\ to trigger SIGQUIT.

To trigger SIGFPE, divide a number by zero.

^C

Caught SIGINT (Ctrl+C): Program interrupted by user.

Case 2: Trigger SIGQUIT (Ctrl+):


$ ./signal_handler

Program started. Waiting for signals.

Press Ctrl+C to trigger SIGINT or Ctrl+\ to trigger SIGQUIT.

To trigger SIGFPE, divide a number by zero.

^\

Caught SIGQUIT (Ctrl+\): Program quit signal received.

Case 3: Trigger SIGFPE (Floating-point exception):


$ ./signal_handler

Program started. Waiting for signals.

Press Ctrl+C to trigger SIGINT or Ctrl+\ to trigger SIGQUIT.

To trigger SIGFPE, divide a number by zero.

Attempting division by zero to simulate SIGFPE...

Caught SIGFPE: Floating-point exception occurred (e.g., division by zero).

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:
EX.NO:
31
DATE: IPC MECHANISMS USING FIFO AND PIPE

AIM:
To implement IPC Mechanism using FIFO and PIPE.
PROCEDURE

1) FIFO (Named Pipe):

I) Create a named pipe using the mkfifo() system call or mknod command.
II) Write one program to write data into the FIFO and another program to read data from it.

2) PIPE (Unnamed Pipe):

I) Use the pipe() system call to create an unnamed pipe for communication between parent and child processes.

3) Compile the programs using GCC and execute them as per the specified roles (reader/writer).

PROGRAMS
(a) FIFO (Named Pipe):

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
const char *fifo = "/tmp/myfifo"; // FIFO file path
char message[100];
// Create a FIFO
if (mkfifo(fifo, 0666) == -1) {
perror("mkfifo");
exit(EXIT_FAILURE);

printf("Enter a message to send: ");

fgets(message, sizeof(message), stdin);

// Open FIFO for writing

32
int fd = open(fifo, O_WRONLY);

if (fd == -1) {

perror("open");

exit(EXIT_FAILURE);

write(fd, message, sizeof(message));

close(fd);

printf("Message sent through FIFO: %s\n", message);

return 0;

(b) PIPE (Unnamed Pipe):

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

int main() {

int pipefd[2]; // Pipe file descriptors

pid_t pid;

char write_msg[] = "Hello from parent process!";

char read_msg[100];

// Create the pipe

if (pipe(pipefd) == -1) {
33
perror("pipe");

exit(EXIT_FAILURE);

pid = fork(); // Create a child process

if (pid < 0) {

perror("fork");

exit(EXIT_FAILURE);

if (pid > 0) { // Parent process

close(pipefd[0]); // Close unused read end

write(pipefd[1], write_msg, strlen(write_msg) + 1);

close(pipefd[1]); // Close write end after writing

} else { // Child process

close(pipefd[1]); // Close unused write end

read(pipefd[0], read_msg, sizeof(read_msg));

close(pipefd[0]); // Close read end after reading

printf("Message received in child process: %s\n", read_msg);

return 0;

34
OUTPUT:

(a) FIFO Output

Terminal 1 (Reader):

$ ./fifo_reader

Message received from FIFO: Hello, FIFO!

(c) PIPE Output:

$ ./pipe_example

Message received in child process: Hello from parent process!

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

35
EX.NO: Implement message queue form of IPC
DATE:

AIM

To implement Inter-Process Communication (IPC) using the message queue mechanism in Linux.

PROCEDURE

1. Use the msgget() system call to create or access a message queue.


2. Use the msgsnd() system call to send messages to the queue.
3. Use the msgrcv() system call to receive messages from the queue.
4. Compile and execute separate sender and receiver programs to demonstrate communication via the message queue.

PROGRAMS
Sender Program:

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

#define KEY 1234

// Structure for message queue


struct msg_buffer {
long msg_type;
char msg_text[100];
} message;

int main() {
int msg_id;

// Create a message queue


msg_id = msgget(KEY, 0666 | IPC_CREAT);
if (msg_id == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}

// Send a message
message.msg_type = 1; // Message type
printf("Enter a message: ");
fgets(message.msg_text, sizeof(message.msg_text), stdin);

if (msgsnd(msg_id, &message, sizeof(message.msg_text), 0) == -1) {


perror("msgsnd");
exit(EXIT_FAILURE);
}

printf("Message sent: %s\n", message.msg_text);


return 0;
}

36
Receiver Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define KEY 1234

// Structure for message queue


struct msg_buffer {
long msg_type;
char msg_text[100];
} message;

int main() {
int msg_id;

// Access the message queue


msg_id = msgget(KEY, 0666 | IPC_CREAT);
if (msg_id == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}

// Receive a message
if (msgrcv(msg_id, &message, sizeof(message.msg_text), 1, 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}

printf("Message received: %s\n", message.msg_text);

// Destroy the message queue


if (msgctl(msg_id, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(EXIT_FAILURE);
}

return 0;
}

Execution Steps:

1) Compile the programs:

gcc -o sender sender.c


37
gcc -o receiver receiver.c

2) Run the receiver program in one terminal:

./receiver

3) Run the sender program in another terminal:

./sender

OUTPUT:
Sender Program Output:

$ ./sender
Enter a message: Hello, Message Queue!
Message sent: Hello, Message Queue!

Receiver Program Output:

$ ./receiver
Message received: Hello, Message Queue!

CRITERIA MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

38
EX.NO: Inter-Process Communication (IPC) using the
DATE:
shared memory mechanism

AIM:
To implement Inter-Process Communication (IPC) using the shared memory mechanism in
Linux.

PROCEDURE

1. Use the shmget() system call to create or access shared memory.


2. Use the shmat() system call to attach the shared memory segment to the process’s address space.
3. Write to or read from the shared memory segment as needed.
4. Use the shmdt() system call to detach the shared memory segment after use.
5. Use the shmctl() system call to remove the shared memory segment if it is no longer required.

PROGRAMS
Writer Program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

#define KEY 1234

int main() {
int shmid;
char *shared_memory;

// Create a shared memory segment


shmid = shmget(KEY, 1024, 0666 | IPC_CREAT);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}

// Attach the shared memory to the process


shared_memory = (char *)shmat(shmid, NULL, 0);
if (shared_memory == (char *)-1) {
perror("shmat");
exit(EXIT_FAILURE);
}

// Write data to the shared memory


printf("Enter some data to write to shared memory: ");
39
fgets(shared_memory, 1024, stdin);
printf("Data written to shared memory: %s\n", shared_memory);

// Detach the shared memory


if (shmdt(shared_memory) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}

return 0;
}

Reader Program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

#define KEY 1234

int main() {
int shmid;
char *shared_memory;

// Access the shared memory segment


shmid = shmget(KEY, 1024, 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}

// Attach the shared memory to the process


shared_memory = (char *)shmat(shmid, NULL, 0);
if (shared_memory == (char *)-1) {
perror("shmat");
exit(EXIT_FAILURE);
}

// Read data from the shared memory


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

// Detach the shared memory


if (shmdt(shared_memory) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
40
// Remove the shared memory segment
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}

return 0;
}

Execution Steps

Compile the programs:

gcc -o writer writer.c

gcc -o reader reader.c

Run the writer program in one terminal:

./writer

Run the reader program in another terminal:

./reader

OUTPUT:

Writer Program Output:


$ ./writer
Enter some data to write to shared memory: Hello, Shared Memory!
Data written to shared memory: Hello, Shared Memory!

Reader Program Output:


$ ./reader
Data read from shared memory: Hello, Shared Memory!

` MAX.MARKS MARKS OBTAINED


AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

41
RESULT:

42
EX.NO: TCP iterative server and client
DATE:
socket program

AIM:

To implement a TCP iterative server and client socket program in C, where the server takes user input for
the port number, binds to the specified port, and waits for client connections.

PROCEDURE

1) Server Program:

1. Create a socket using the socket() system call.


2. Accept a port number as input and bind the socket to the given port using bind().
3. Listen for incoming connections using listen().
4. Accept and handle client connections using accept() and communicate using send() and recv().

2) Client Program:

1. Create a socket using the socket() system call.


2. Connect to the server using connect() by providing the server's IP address and port.
3. Send and receive data using send() and recv().

3) Close the sockets after communication using close().

PROGRAM:
Server Program (TCP Iterative Server):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

int main() {
int server_fd, client_fd, port;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len;
char buffer[BUFFER_SIZE];

// Create socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
43
perror("Socket creation failed");
exit(EXIT_FAILURE);
}

// Input port number


printf("Enter the port number to bind: ");
scanf("%d", &port);

// Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);

// Bind socket to port


if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}

// Listen for connections


if (listen(server_fd, 5) == -1) {
perror("Listen failed");
close(server_fd);
exit(EXIT_FAILURE);
}

printf("Server is listening on port %d...\n", port);

while (1) {
client_len = sizeof(client_addr);
// Accept client connection
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1) {
perror("Accept failed");
continue;
}

printf("Connection established with client.\n");

// Receive data from client


memset(buffer, 0, BUFFER_SIZE);
recv(client_fd, buffer, BUFFER_SIZE, 0);
printf("Client: %s\n", buffer);

// Echo back the message


44
send(client_fd, buffer, strlen(buffer), 0);

// Close client socket


close(client_fd);
}

// Close server socket


close(server_fd);
return 0;
}

Client Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
char server_ip[16];
int port;

// Input server details


printf("Enter server IP address: ");
scanf("%s", server_ip);
printf("Enter server port number: ");
scanf("%d", &port);

// Create socket
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}

// Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) {
perror("Invalid address");
close(client_fd);
exit(EXIT_FAILURE);
45
}

// Connect to server
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Connection failed");
close(client_fd);
exit(EXIT_FAILURE);
}

printf("Connected to server.\n");

// Send and receive messages


while (1) {
printf("Enter message to send (type 'exit' to quit): ");
scanf(" %[^\n]", buffer);

if (strcmp(buffer, "exit") == 0) {
printf("Exiting...\n");
break;
}

send(client_fd, buffer, strlen(buffer), 0);


memset(buffer, 0, BUFFER_SIZE);
recv(client_fd, buffer, BUFFER_SIZE, 0);
printf("Server: %s\n", buffer);
}

// Close client socket


close(client_fd);
return 0;
}

Execution Steps

Compile the programs:

gcc -o server server.c

gcc -o client client.c

Run the server program in one terminal:

./server

46
Run the client program in another terminal:

./client

Communicate:

 Enter messages in the client terminal.


 Observe the server echoing the messages back.

OUTPUT:

Server Output:
Enter the port number to bind: 8080
Server is listening on port 8080...
Connection established with client.
Client: Hello, Server!

Client Output:
Enter server IP address: 127.0.0.1
Enter server port number: 8080
Connected to server.
Enter message to send (type 'exit' to quit): Hello, Server!
Server: Hello, Server!
Enter message to send (type 'exit' to quit): exit
Exiting...

47
` MAX.MARKS MARKS OBTAINED
AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

48
EX.NO:
DATE: TCP iterative server-client program

AIM:
To implement a TCP iterative server-client program in C, where the server
accepts client connections, communicates using recv() and send() functions, and
handles the communication iteratively.
Procedure

Setup Environment:

1. Ensure a Linux-based system or terminal with GCC compiler is available.


2. Verify networking tools and permissions are configured correctly for socket communication.

Write the Server Code:

1. Create a server program that accepts a port number as input.


2. Use the socket(), bind(), listen(), and accept() functions to create a listening server.
3. Handle client requests iteratively using recv() and send() functions for communication.
4. Close the client socket after communication ends.

Write the Client Code:

1. Create a client program that connects to the server using its IP address and port number.
2. Use the socket() and connect() functions to establish a connection to the server.
3. Send and receive messages using send() and recv() functions.
4. Close the socket upon user request or termination.

Compile the Programs:

1. Use the GCC compiler to compile the server and client programs separately.

Execute the Programs:

1. Run the server program in one terminal.


2. Run the client program in another terminal, providing the server's IP and port.
3. Exchange messages between the server and client.

Validate Communication:

1. Send multiple messages from the client to the server and verify that the server echoes responses.
2. Ensure that the connection terminates gracefully when the client sends an exit message.

Document Results:

49
1. Record the input, output, and observed behavior of the server and client during communication.
2. Note any errors or edge cases encountered and how they were resolved.

PROGRAM:

Server Program (TCP Iterative Server):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

int main() {
int server_fd, client_fd, port;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len;
char buffer[BUFFER_SIZE];

// Step 1: Create a socket


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}

// Step 2: Input port number


printf("Enter the port number to bind: ");
scanf("%d", &port);

// Step 3: Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY; // Accept connections on any network
interface
server_addr.sin_port = htons(port); // Convert port to network byte order

// Step 4: Bind the socket to the specified port


if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}

// Step 5: Listen for incoming connections


50
if (listen(server_fd, 5) == -1) { // Queue size of 5
perror("Listen failed");
close(server_fd);
exit(EXIT_FAILURE);
}

printf("Server is listening on port %d...\n", port);

while (1) {
// Step 6: Accept a client connection
client_len = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1) {
perror("Accept failed");
continue; // Continue accepting other clients
}

printf("Connection established with client.\n");

while (1) {
// Step 7: Receive data from the client
memset(buffer, 0, BUFFER_SIZE);
int bytes_received = recv(client_fd, buffer, BUFFER_SIZE, 0);

if (bytes_received == -1) {
perror("Receive failed");
break;
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
break;
}

printf("Client: %s\n", buffer);

// Step 8: Send a response back to the client


char response[BUFFER_SIZE];
sprintf(response, "Server received: %s", buffer);
send(client_fd, response, strlen(response), 0);
}

// Step 9: Close the client socket


close(client_fd);
}

// Step 10: Close the server socket (Unreachable in this loop but added for
completeness)
51
close(server_fd);
return 0;
}

Client Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
char server_ip[16];
int port;

// Step 1: Input server details


printf("Enter server IP address: ");
scanf("%s", server_ip);
printf("Enter server port number: ");
scanf("%d", &port);

// Step 2: Create a socket


if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}

// Step 3: Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);

// Convert IP address to binary form


if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) {
perror("Invalid address or address not supported");
close(client_fd);
exit(EXIT_FAILURE);
}

// Step 4: Connect to the server


52
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Connection failed");
close(client_fd);
exit(EXIT_FAILURE);
}

printf("Connected to server.\n");

// Step 5: Communicate with the server


while (1) {
printf("Enter message to send (type 'exit' to quit): ");
scanf(" %[^\n]", buffer);

if (strcmp(buffer, "exit") == 0) {
printf("Exiting...\n");
break;
}

send(client_fd, buffer, strlen(buffer), 0);

memset(buffer, 0, BUFFER_SIZE);
recv(client_fd, buffer, BUFFER_SIZE, 0);
printf("Server: %s\n", buffer);
}

// Step 6: Close the client socket


close(client_fd);
return 0;
}

53
Execution Steps

Compile the programs:

gcc -o server server.c

gcc -o client client.c

Run the server program in one terminal:

./server

Run the client program in another terminal:

./client

Test Communication:
· In the client terminal, type messages to send to the server.
· Observe the server's response echoing the received messages.

OUTPUT
Server Output:

Enter the port number to bind: 8080


Server is listening on port 8080...
Connection established with client.
Client: Hello Server
Client: How are you?

Client Output:

Enter server IP address: 127.0.0.1


Enter server port number: 8080
Connected to server.
Enter message to send (type 'exit' to quit): Hello Server
Server: Server received: Hello Server
Enter message to send (type 'exit' to quit): How are you?
Server: Server received: How are you?
Enter message to send (type 'exit' to quit): exit
Exiting...

54
CRITERIA MAX.MARKS MARKS OBTAINED
AIM & ALGORITHM 5
EXECUTION & OUTPUT 10
VIVA 10
TOTAL 25

RESULT:

55

You might also like