0% found this document useful (0 votes)
2 views41 pages

Internal Lab

Uploaded by

venkata.chinna
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)
2 views41 pages

Internal Lab

Uploaded by

venkata.chinna
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

SATHIRAM ENGINEERING COLLEGE: NANDYAL

(Approved by AICTE, New Delhi and Permanently Affiliated to JNTUA, Ananthapuramu)

INTERNAL LAB

SUBJECT CODE: 23A31506 SUBJECT NAME: SYSTEM SOFTWARE PRAMMING


DATE: 17.10.2025(FRIDAY)

1. Write simple programs in Prolog for facts, rules, and queries.


2. Develop a Prolog-based expert system for medical diagnosis or animal identification.
3. Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in Python.
4. Implement A* Search Algorithm using heuristics in Python.
5. Implement the Mini max algorithm for a simple game (e.g., Tic Tac Toe).
6. Design and implement a two-pass assembler in C.
7. Implement a Macro Processor using C for assembly language programs.
8. Develop a simple Linux Shell (command interpreter) using C.
9. Write shell scripts for file operations, process creation, and monitoring.
10. Demonstrate inter-process communication using pipes and signals in Linux.
11. Integrate AI logic (search/expert system) into a shell script or system utility for task
automation.
12. Develop an AI-powered system utility (e.g., Intelligent File Manager, AI Bot for CLI
commands).
1. Write simple programs in Prolog for facts, rules, and queries.

% --- FACTS ---


% parent(Parent, Child).
parent(john, mary).
parent(john, mike).
parent(susan, mary).
parent(susan, mike).
parent(mary, lisa).
parent(mike, tom).

% male(Name).
male(john).
male(mike).
male(tom).

% female(Name).
female(susan).
female(mary).
female(lisa).

% --- RULES ---


% father(F, C) :- F is the father of C if F is a parent of C and F is male.
father(F, C) :-
parent(F, C),
male(F).
% mother(M, C) :- M is the mother of C if M is a parent of C and M is female.
mother(M, C) :-
parent(M, C),
female(M).

% sibling(X, Y) :- X and Y are siblings if they share a parent and are not the same person.
sibling(X, Y) :-
parent(P, X),
parent(P, Y),
X \= Y.

% grandparent(GP, GC) :- GP is grandparent of GC if GP is parent of P and P is parent of


GC.
grandparent(GP, GC) :-
parent(GP, P),
parent(P, GC).

OUTPUT
?- father(john, X). Who are John’s children? X = mary ; X = mike.

?- mother(susan, X). Who are Susan’s children? X = mary ; X = mike.

?- sibling(mary, X). Who are Mary’s siblings? X = mike.

?- grandparent(john, X). Who are John’s grandchildren? X = lisa ; X = tom.

?- parent(X, mary). Who are Mary’s parents? X = john ; X = susan.

[Link] a Prolog-based expert system for medical diagnosis or animal identification.

% --- Rules for diseases based on symptoms ---


disease(flu) :-
symptom(fever),
symptom(cough),
symptom(sore_throat),
symptom(body_ache).

disease(cold) :-
symptom(runny_nose),
symptom(sneezing),
symptom(sore_throat).

disease(malaria) :-
symptom(fever),
symptom(chills),
symptom(sweating),
symptom(headache).

disease(typhoid) :-
symptom(fever),
symptom(abdominal_pain),
symptom(loss_of_appetite),
symptom(headache).

disease(covid19) :-
symptom(fever),
symptom(cough),
symptom(shortness_of_breath),
symptom(loss_of_taste_or_smell).

% --- Asking questions interactively ---


ask(Question) :-
write('Do you have '), write(Question), write('? (yes/no): '),
read(Response),
(Response == yes ->
assert(symptom(Question));
fail).
% --- Start diagnosis ---
diagnose :-
retractall(symptom(_)), % clear previous symptoms
( disease(Disease)
-> format('You may have ~w.~n', [Disease])
; write('Sorry, your symptoms do not match any known disease.'), nl).

% --- Facts about possible symptoms (for prompting user) ---


symptom_list([
fever, cough, sore_throat, body_ache, runny_nose, sneezing,
chills, sweating, headache, abdominal_pain, loss_of_appetite,
shortness_of_breath, loss_of_taste_or_smell
]).

% --- Interactive interface ---


start :-
write('--- Welcome to the Medical Diagnosis Expert System ---'), nl,
symptom_list(Symptoms),
ask_symptoms(Symptoms),
diagnose.

ask_symptoms([]).
ask_symptoms([H|T]) :-
ask(H),
ask_symptoms(T).

OUTPUT
?- [medical_diagnosis].
?- start.
--- Welcome to the Medical Diagnosis Expert System ---
Do you have fever? (yes/no): yes
Do you have cough? (yes/no): yes
Do you have sore_throat? (yes/no): yes
Do you have body_ache? (yes/no): yes
...
You may have flu.

3. Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in Python.

# ------------------------------------------
# Graph Traversal using DFS and BFS in Python
# ------------------------------------------

from collections import deque

# Define the graph using an adjacency list


graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

# --------------------------
# Depth-First Search (DFS)
# --------------------------
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
[Link](start)
print(start, end=' ')
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# --------------------------
# Breadth-First Search (BFS)
# --------------------------
def bfs(graph, start):
visited = set()
queue = deque([start])
[Link](start)

while queue:
vertex = [Link]()
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
[Link](neighbor)
[Link](neighbor)

# --------------------------
# Main Program
# --------------------------
if __name__ == "__main__":
print("Graph Traversal using DFS and BFS\n")

print("Depth-First Search (DFS):")


dfs(graph, 'A') # Starting node: A
print("\n")

print("Breadth-First Search (BFS):")


bfs(graph, 'A') # Starting node: A
print()
output
Graph Traversal using DFS and BFS

Depth-First Search (DFS):


ABDEFC

Breadth-First Search (BFS):


ABCDEF

[Link] A* Search Algorithm using heuristics in Python.

# ---------------------------------------------
# A* Search Algorithm Implementation in Python
# ---------------------------------------------

from heapq import heappush, heappop

# Example graph represented as adjacency list with costs


graph = {
'A': {'B': 1, 'C': 4},
'B': {'C': 2, 'D': 5},
'C': {'D': 1},
'D': {'E': 3},
'E': {}
}

# Heuristic values (estimated cost to goal)


# These values are typically problem-specific.
heuristic = {
'A': 7,
'B': 6,
'C': 2,
'D': 1,
'E': 0
}

# -----------------------------------------------------
# A* Search Algorithm Function
# -----------------------------------------------------
def a_star_search(graph, start, goal, heuristic):
# Priority queue for frontier nodes (min-heap)
open_list = []
heappush(open_list, (0 + heuristic[start], 0, start, [start])) # (f, g, node, path)

visited = set()

while open_list:
f, g, current, path = heappop(open_list)

if current in visited:
continue
[Link](current)

# If goal found
if current == goal:
print("Path found:", " -> ".join(path))
print("Total cost:", g)
return

# Explore neighbors
for neighbor, cost in graph[current].items():
if neighbor not in visited:
g_new = g + cost
f_new = g_new + heuristic[neighbor]
heappush(open_list, (f_new, g_new, neighbor, path + [neighbor]))

print("No path found.")


# -----------------------------------------------------
# Main Program
# -----------------------------------------------------
if __name__ == "__main__":
print("A* Search Algorithm Example\n")

start_node = 'A'
goal_node = 'E'

print(f"Finding path from {start_node} to {goal_node}...\n")


a_star_search(graph, start_node, goal_node, heuristic)

OUTPUT
A* Search Algorithm Example

Finding path from A to E...

Path found: A -> C -> D -> E


Total cost: 8

[Link] the Mini max algorithm for a simple game (e.g., Tic Tac Toe).

# ---------------------------------------------------
# Tic Tac Toe Game with Minimax Algorithm (Human vs AI)
# ---------------------------------------------------

import math

# Initialize the game board


board = [" " for _ in range(9)]

# Function to print the board


def print_board():
print()
for i in range(3):
print(" | ".join(board[i*3:(i+1)*3]))
if i < 2:
print("---------")
print()

# Function to check if a player has won


def check_winner(b, player):
win_conditions = [
[0,1,2], [3,4,5], [6,7,8], # rows
[0,3,6], [1,4,7], [2,5,8], # columns
[0,4,8], [2,4,6] # diagonals
]
for combo in win_conditions:
if all(b[i] == player for i in combo):
return True
return False

# Check if the board is full (draw)


def is_draw(b):
return " " not in b

# -----------------------------
# Minimax Algorithm Definition
# -----------------------------
def minimax(b, depth, is_maximizing):
# Base cases
if check_winner(b, "O"):
return 1
elif check_winner(b, "X"):
return -1
elif is_draw(b):
return 0
if is_maximizing: # AI’s turn
best_score = -[Link]
for i in range(9):
if b[i] == " ":
b[i] = "O"
score = minimax(b, depth + 1, False)
b[i] = " "
best_score = max(score, best_score)
return best_score
else: # Human’s turn
best_score = [Link]
for i in range(9):
if b[i] == " ":
b[i] = "X"
score = minimax(b, depth + 1, True)
b[i] = " "
best_score = min(score, best_score)
return best_score

# Function to find the best move for the AI


def best_move():
best_score = -[Link]
move = None
for i in range(9):
if board[i] == " ":
board[i] = "O"
score = minimax(board, 0, False)
board[i] = " "
if score > best_score:
best_score = score
move = i
return move
# -----------------------------
# Main Game Loop
# -----------------------------
def play_game():
print("Welcome to Tic Tac Toe!")
print("You are X, AI is O.")
print_board()

while True:
# Human move
try:
user_move = int(input("Enter your move (1-9): ")) - 1
if user_move < 0 or user_move > 8 or board[user_move] != " ":
print("Invalid move! Try again.")
continue
except ValueError:
print("Please enter a valid number (1-9).")
continue

board[user_move] = "X"

# Check if human wins


if check_winner(board, "X"):
print_board()
print("🎉 You win!")
break

# Check for draw


if is_draw(board):
print_board()
print("🤝 It's a draw!")
break

# AI move
print("AI is thinking...")
ai_move = best_move()
board[ai_move] = "O"

print_board()

# Check if AI wins
if check_winner(board, "O"):
print("💻 AI wins!")
break

# Check for draw


if is_draw(board):
print("🤝 It's a draw!")
break

# Run the game


if __name__ == "__main__":
play_game()

output

Welcome to Tic Tac Toe!


You are X, AI is O.

| |
---------
| |
---------
| |

Enter your move (1-9): 5


AI is thinking...
O| |
---------
|X|
---------
| |

💻 AI wins!

Design and implement a two-pass assembler in C,


/*
------------------------------------------------------------
Simple Two-Pass Assembler in C
Author: Example Educational Implementation
Description:
- Demonstrates how a two-pass assembler works.
- Assembly language format:
LABEL OPCODE OPERAND
- Example input file ([Link]):
START 100
LOOP MOVER AREG,NUM
ADD BREG,ONE
SUB CREG,TWO
MOVEM AREG,RESULT
END
NUM DS 1
ONE DC 1
TWO DC 2
RESULT DS 1
------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 50

// Symbol table structure


struct symbol {
char label[10];
int addr;
} symtab[MAX];

int symcount = 0;
int locctr = 0;

// Opcode table (simplified)


struct opcode {
char mnemonic[10];
char code[10];
} optab[] = {
{"START", ""},
{"MOVER", "01"},
{"MOVEM", "02"},
{"ADD", "03"},
{"SUB", "04"},
{"MUL", "05"},
{"DIV", "06"},
{"DC", ""},
{"DS", ""},
{"END", ""}
};

int search_optab(char *opcode) {


for (int i = 0; i < 10; i++)
if (strcmp(optab[i].mnemonic, opcode) == 0)
return i;
return -1;
}

int search_symtab(char *symbol) {


for (int i = 0; i < symcount; i++)
if (strcmp(symtab[i].label, symbol) == 0)
return i;
return -1;
}

void pass1(FILE *fp1) {


char label[10], opcode[10], operand[10];
int i, len;

printf("\nPASS 1:\n");
fscanf(fp1, "%s", opcode);

if (strcmp(opcode, "START") == 0) {
fscanf(fp1, "%d", &locctr);
printf("Starting address = %d\n", locctr);
} else {
locctr = 0;
rewind(fp1);
}

while (fscanf(fp1, "%s", label) != EOF) {


if (strcmp(label, "END") == 0)
break;

fscanf(fp1, "%s%s", opcode, operand);

// Label present?
if (strcmp(label, "**") != 0) {
strcpy(symtab[symcount].label, label);
symtab[symcount].addr = locctr;
symcount++;
}

int opIndex = search_optab(opcode);

if (opIndex == -1)
printf("Error: Invalid opcode %s\n", opcode);
else if (strcmp(opcode, "DS") == 0)
locctr += atoi(operand);
else if (strcmp(opcode, "DC") == 0)
locctr += 1;
else
locctr += 1;
}

printf("\nSymbol Table:\n");
printf("Label\tAddress\n");
for (i = 0; i < symcount; i++)
printf("%s\t%d\n", symtab[i].label, symtab[i].addr);

printf("Program length = %d\n", locctr);


}

void pass2(FILE *fp2) {


char label[10], opcode[10], operand[10];
int i, symIndex, opIndex;

printf("\nPASS 2: Object Code Generation\n");

rewind(fp2);
fscanf(fp2, "%s", opcode);
if (strcmp(opcode, "START") == 0) {
fscanf(fp2, "%s", operand);
} else {
rewind(fp2);
}

while (fscanf(fp2, "%s", label) != EOF) {


if (strcmp(label, "END") == 0)
break;

fscanf(fp2, "%s%s", opcode, operand);

opIndex = search_optab(opcode);

if (opIndex == -1)
printf("Error: Unknown opcode %s\n", opcode);
else if (strcmp(opcode, "DC") == 0)
printf("%s\t%s\t%s\t-->\t%s\n", label, opcode, operand, operand);
else if (strcmp(opcode, "DS") == 0)
printf("%s\t%s\t%s\t-->\t(No code)\n", label, opcode, operand);
else {
symIndex = search_symtab(operand);
if (symIndex == -1)
printf("%s\t%s\t%s\t-->\t%s ?\n", label, opcode, operand, optab[opIndex].code);
else
printf("%s\t%s\t%s\t-->\t%s %d\n", label, opcode, operand, optab[opIndex].code,
symtab[symIndex].addr);
}
}
}

int main() {
FILE *fp;
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}

pass1(fp);
rewind(fp);
pass2(fp);

fclose(fp);
return 0;
}

START 100
LOOP MOVER AREG,NUM
** ADD BREG,ONE
** SUB CREG,TWO
** MOVEM AREG,RESULT
END
NUM DS 1
ONE DC 1
TWO DC 2
RESULT DS 1

OUTPUT
PASS 1:
Starting address = 100

Symbol Table:
Label Address
LOOP 100
NUM 104
ONE 105
TWO 106
RESULT 107
Program length = 108

PASS 2: Object Code Generation


LOOP MOVER AREG,NUM --> 01 104
** ADD BREG,ONE --> 03 105
** SUB CREG,TWO --> 04 106
** MOVEM AREG,RESULT--> 02 107

7. Implement a Macro Processor using C for assembly language programs.

/*
---------------------------------------------------------------
Simple Macro Processor in C
Author: Educational Example
Description:
- Reads assembly code with macros.
- Builds:
MNT: Macro Name Table
MDT: Macro Definition Table
- Expands macros in the output file.
Example Input ([Link]):

MACRO
INCR &A,&B
LDA &A
ADD &B
STA &A
MEND

START
INCR NUM1, NUM2
INCR TOTAL, FIVE
END

---------------------------------------------------------------
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 50

// ---------- Structures ----------


struct MNT {
char name[20];
int mdt_index;
} mnt[MAX];

char mdt[MAX][50];
int mntc = 0, mdtc = 0;

// ---------- Functions ----------


void pass1(FILE *fp) {
char line[80], label[20], opcode[20], operand[40];
char temp[50];

while (fgets(line, sizeof(line), fp)) {


sscanf(line, "%s", opcode);

if (strcmp(opcode, "MACRO") == 0) {
// Read macro prototype
fgets(line, sizeof(line), fp);
sscanf(line, "%s %s", mnt[mntc].name, operand);
mnt[mntc].mdt_index = mdtc;
mntc++;

// Read macro body


while (fgets(line, sizeof(line), fp)) {
sscanf(line, "%s", opcode);
if (strcmp(opcode, "MEND") == 0) {
strcpy(mdt[mdtc++], "MEND");
break;
}
strcpy(mdt[mdtc++], line);
}
}
}
}

void displayTables() {
printf("\nMACRO NAME TABLE (MNT):\n");
printf("Index\tName\tMDT Index\n");
for (int i = 0; i < mntc; i++)
printf("%d\t%s\t%d\n", i + 1, mnt[i].name, mnt[i].mdt_index);

printf("\nMACRO DEFINITION TABLE (MDT):\n");


for (int i = 0; i < mdtc; i++)
printf("%d\t%s", i, mdt[i]);
}

void expand(FILE *fp, FILE *fpout) {


char line[80], label[20], opcode[20], operand[40];
int i;
rewind(fp);

while (fgets(line, sizeof(line), fp)) {


sscanf(line, "%s", opcode);

if (strcmp(opcode, "MACRO") == 0) {
// Skip macro definition
while (fgets(line, sizeof(line), fp)) {
sscanf(line, "%s", opcode);
if (strcmp(opcode, "MEND") == 0)
break;
}
} else {
int found = -1;
for (i = 0; i < mntc; i++) {
if (strcmp(opcode, mnt[i].name) == 0) {
found = i;
break;
}
}

if (found != -1) {
// Expand macro
int k = mnt[found].mdt_index;
while (strcmp(mdt[k], "MEND") != 0) {
fprintf(fpout, "%s", mdt[k]);
k++;
}
} else {
fprintf(fpout, "%s", line);
}
}
}
}
int main() {
FILE *fp, *fpout;
fp = fopen("[Link]", "r");
fpout = fopen("[Link]", "w");

if (fp == NULL || fpout == NULL) {


printf("Error: Unable to open file.\n");
exit(1);
}

// Pass 1: Build MNT & MDT


pass1(fp);

// Display tables
displayTables();

// Pass 2: Macro Expansion


expand(fp, fpout);

printf("\n\nMacro expansion completed. Check '[Link]'.\n");

fclose(fp);
fclose(fpout);
return 0;
}

Output
MACRO NAME TABLE (MNT):
Index Name MDT Index
1 INCR 0

MACRO DEFINITION TABLE (MDT):


0 LDA &A
1 ADD &B
2 STA &A
3 MEND

Macro expansion completed. Check '[Link]'.

[Link] a simple Linux Shell (command interpreter) using C.

/*
-------------------------------------------------------------
Simple Linux Shell in C
Author: Educational Example
Description:
- A basic shell that executes Linux commands.
- Supports built-in commands:
cd <dir> → change directory
exit → exit the shell
- Uses fork(), execvp(), and wait().
-------------------------------------------------------------
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAX_INPUT 1024


#define MAX_ARGS 64

// Function to read a command from the user


void read_command(char *input) {
printf("myshell> ");
fflush(stdout);
if (fgets(input, MAX_INPUT, stdin) == NULL) {
printf("\n");
exit(0); // handle Ctrl+D
}
// Remove newline
input[strcspn(input, "\n")] = '\0';
}

// Function to split the command into arguments (tokenize)


void parse_command(char *input, char **args) {
char *token;
int index = 0;

token = strtok(input, " ");


while (token != NULL && index < MAX_ARGS - 1) {
args[index++] = token;
token = strtok(NULL, " ");
}
args[index] = NULL;
}

// Function to execute a command


void execute_command(char **args) {
pid_t pid;
int status;

if (args[0] == NULL) {
return; // Empty command
}

// Built-in 'exit'
if (strcmp(args[0], "exit") == 0) {
printf("Exiting shell...\n");
exit(0);
}

// Built-in 'cd'
if (strcmp(args[0], "cd") == 0) {
if (args[1] == NULL) {
fprintf(stderr, "cd: missing argument\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd failed");
}
}
return;
}

// Fork a child process


pid = fork();

if (pid < 0) {
perror("Fork failed");
return;
} else if (pid == 0) {
// Child process: execute the command
if (execvp(args[0], args) == -1) {
perror("Command not found");
}
exit(EXIT_FAILURE);
} else {
// Parent process: wait for the child to finish
waitpid(pid, &status, 0);
}
}
int main() {
char input[MAX_INPUT];
char *args[MAX_ARGS];

printf("======================================\n");
printf(" Simple Linux Shell in C (myshell) \n");
printf(" Type 'exit' to quit.\n");
printf("======================================\n");

while (1) {
read_command(input);
parse_command(input, args);
execute_command(args);
}

return 0;
}

Output
======================================
Simple Linux Shell in C (myshell)
Type 'exit' to quit.
======================================
myshell> pwd
/home/user

myshell> ls
Documents Downloads main.c myshell Pictures

myshell> cd Documents
myshell> pwd
/home/user/Documents
myshell> echo Hello World
Hello World

myshell> exit
Exiting shell...

[Link] shell scripts for file operations, process creation, and monitoring.
#!/bin/bash
# -----------------------------------------------
# File Operations Script
# Demonstrates file creation, copying, renaming, and deletion
# -----------------------------------------------

echo "=== FILE OPERATIONS ==="

# Create a new file


echo "Enter a filename to create:"
read filename
touch "$filename"
echo "File '$filename' created."

# Write some content into it


echo "Enter some text to store in the file:"
read text
echo "$text" > "$filename"
echo "Text written to $filename."

# Display file content


echo "Content of $filename:"
cat "$filename"

# Copy file
echo "Enter name of copy file:"
read copyname
cp "$filename" "$copyname"
echo "File copied as '$copyname'."

# Rename file
echo "Enter new name to rename '$filename':"
read newname
mv "$filename" "$newname"
echo "File renamed to '$newname'."

# Delete file
echo "Do you want to delete '$copyname'? (y/n)"
read ans
if [ "$ans" = "y" ]; then
rm "$copyname"
echo "File '$copyname' deleted."
else
echo "File not deleted."
Fi
Run command
chmod +x file_operations.sh
./file_operations.sh

#!/bin/bash
# --------------------------------------------------
# Process Creation Script
# Demonstrates creating background and foreground processes
# --------------------------------------------------

echo "=== PROCESS CREATION ==="

echo "Running 'sleep 5' in foreground..."


sleep 5
echo "Foreground process finished."
echo "Now running 'sleep 10' in background..."
sleep 10 &
bg_pid=$!
echo "Background process created with PID: $bg_pid"

echo "You can check it with: ps -p $bg_pid"


echo "Waiting for background process to finish..."
wait $bg_pid
echo "Background process completed."

=== PROCESS CREATION ===


Running 'sleep 5' in foreground...
Foreground process finished.
Now running 'sleep 10' in background...
Background process created with PID: 12452
You can check it with: ps -p 12452
Waiting for background process to finish...
Background process completed.
OUTPUT
=== PROCESS MONITORING ===
Enter process name to monitor (e.g., bash, firefox, sshd):
firefox
Process 'firefox' is running with PID: 8923
Checking again in 5 seconds... (Press Ctrl+C to stop)
Process 'firefox' is running with PID: 8923
Checking again in 5 seconds...
PROCESS AND MONITAR

#!/bin/bash
# --------------------------------------------------
# Process Monitoring Script
# Monitors a given process name and reports its status
# --------------------------------------------------
echo "=== PROCESS MONITORING ==="
echo "Enter process name to monitor (e.g., bash, firefox, sshd):"
read pname

while true
do
pid=$(pgrep "$pname" | head -n 1)
if [ -z "$pid" ]; then
echo "Process '$pname' is NOT running."
else
echo "Process '$pname' is running with PID: $pid"
fi
echo "Checking again in 5 seconds... (Press Ctrl+C to stop)"
sleep 5
done

OUTPUT

=== PROCESS MONITORING ===


Enter process name to monitor (e.g., bash, firefox, sshd):
firefox
Process 'firefox' is running with PID: 8923
Checking again in 5 seconds... (Press Ctrl+C to stop)
Process 'firefox' is running with PID: 8923
Checking again in 5 seconds...

[Link] inter-process communication using pipes and signals in Linux.


/*
------------------------------------------------------------
Inter-Process Communication Demo
Using Pipes and Signals in Linux
------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>

int pipefd[2]; // pipe file descriptors

// Signal handler for child


void sig_handler(int sig) {
if (sig == SIGUSR1) {
char buffer[100];
read(pipefd[0], buffer, sizeof(buffer)); // read from pipe
printf("Child received message via pipe: %s\n", buffer);
}
}

int main() {
pid_t pid;

// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe failed");
exit(1);
}

// Fork a child process


pid = fork();

if (pid < 0) {
perror("fork failed");
exit(1);
}
else if (pid == 0) {
// -------- Child Process --------
close(pipefd[1]); // close write end

// Set up signal handler


signal(SIGUSR1, sig_handler);

printf("Child PID: %d waiting for signal...\n", getpid());


OUTPUT
Parent PID: 12345
Enter a message to send to child: Hello from Parent
Child PID: 12346 waiting for signal...
Child received message via pipe: Hello from Parent

[Link] AI logic (search/expert system) into a shell script or system utility for task
automation.

#!/bin/bash
# ---------------------------------------------------
# AI Logic in Shell Script - System Helper Expert
# ---------------------------------------------------
# This script recommends actions based on system state
# Uses simple rule-based AI (if-then logic)
# ---------------------------------------------------

echo "Welcome to SysHelper - AI-powered System Utility"

# Function to check CPU load


check_cpu() {
cpu_load=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
echo "Current CPU usage: $cpu_load%"
if (( $(echo "$cpu_load > 70" | bc -l) )); then
echo "AI Suggestion: CPU usage is high! Consider killing unnecessary processes."
else
echo "CPU usage is normal."
fi
}

# Function to check memory usage


check_memory() {
mem_free=$(free -m | awk '/Mem:/ {print $4}')
echo "Free memory: ${mem_free}MB"
if [ "$mem_free" -lt 500 ]; then
echo "AI Suggestion: Low memory! Consider closing some applications."
else
echo "Memory is sufficient."
fi
}

# Function to check disk usage


check_disk() {
disk_use=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
echo "Disk usage: ${disk_use}%"
if [ "$disk_use" -gt 80 ]; then
echo "AI Suggestion: Disk usage is high! Consider cleaning temp files."
else
echo "Disk usage is fine."
fi
}

# Function to suggest based on top process


suggest_process() {
top_proc=$(ps -eo pid,comm,%cpu --sort=-%cpu | head -n 2 | tail -n1)
proc_name=$(echo $top_proc | awk '{print $2}')
proc_cpu=$(echo $top_proc | awk '{print $3}')
echo "Top CPU consuming process: $proc_name ($proc_cpu%)"
if (( $(echo "$proc_cpu > 50" | bc -l) )); then
echo "AI Suggestion: $proc_name is consuming high CPU. Consider investigating or
killing it."
fi
}

# Main AI loop
while true; do
echo
echo "Choose a system check:"
echo "1. CPU Usage"
echo "2. Memory Usage"
echo "3. Disk Usage"
echo "4. Top Process Suggestion"
echo "5. Exit"
read -p "Enter your choice [1-5]: " choice

case $choice in
1) check_cpu ;;
2) check_memory ;;
3) check_disk ;;
4) suggest_process ;;
5) echo "Exiting SysHelper..."; exit 0 ;;
*) echo "Invalid choice. Try again." ;;
esac
done
OUTPUT
Welcome to SysHelper - AI-powered System Utility
Choose a system check:
1. CPU Usage
2. Memory Usage
3. Disk Usage
4. Top Process Suggestion
5. Exit
Enter your choice [1-5]: 1
Current CPU usage: 82%
AI Suggestion: CPU usage is high! Consider killing unnecessary processes.

Enter your choice [1-5]: 3


Disk usage: 45%
Disk usage is fine.

12. Develop an AI-powered system utility (e.g., Intelligent File Manager, AI Bot for CLI
commands).

#!/bin/bash
# -------------------------------------------------------
# AI File Manager - Intelligent CLI Utility
# -------------------------------------------------------
# Features:
# - Lists files intelligently
# - Suggests deletion of large files
# - Finds duplicate files
# - Organizes files by type
# - Rule-based AI logic for recommendations
# -------------------------------------------------------

echo "=========================================="
echo " AI-Powered Intelligent File Manager"
echo "=========================================="

# Function to list files with size info


list_files() {
echo "Files in current directory:"
ls -lh | awk '{print $9, $5}'
}

# Function to suggest large files for cleanup


suggest_large_files() {
echo "Scanning for files larger than 100MB..."
large_files=$(find . -maxdepth 1 -type f -size +100M)
if [ -z "$large_files" ]; then
echo "No large files detected. All good!"
else
echo "AI Suggestion: Consider deleting or archiving these large files:"
echo "$large_files"
fi
}

# Function to find duplicate files based on checksum


find_duplicates() {
echo "Finding duplicate files based on checksum..."
duplicates=$(find . -type f -exec md5sum {} + | sort | uniq -w32 -dD)
if [ -z "$duplicates" ]; then
echo "No duplicates found."
else
echo "AI Suggestion: Duplicate files detected:"
echo "$duplicates"
fi
}

# Function to organize files by type


organize_by_type() {
echo "Organizing files by type..."
for file in *.*; do
[ -f "$file" ] || continue
ext="${file##*.}"
mkdir -p "$ext"
mv "$file" "$ext/"
done
echo "Files have been organized by file type."
}
# AI Menu Loop
while true; do
echo
echo "Choose an action:"
echo "1. List files"
echo "2. Suggest large files for cleanup"
echo "3. Find duplicate files"
echo "4. Organize files by type"
echo "5. Exit"
read -p "Enter choice [1-5]: " choice

case $choice in
1) list_files ;;
2) suggest_large_files ;;
3) find_duplicates ;;
4) organize_by_type ;;
5) echo "Exiting AI File Manager..."; exit 0 ;;
*) echo "Invalid choice. Try again." ;;
esac
done
output

==========================================
AI-Powered Intelligent File Manager
==========================================
Choose an action:
1. List files
2. Suggest large files for cleanup
3. Find duplicate files
4. Organize files by type
5. Exit
Enter choice [1-5]: 2
Scanning for files larger than 100MB...
AI Suggestion: Consider deleting or archiving these large files:
./movie.mp4
./[Link]

You might also like