0% found this document useful (0 votes)
29 views37 pages

UNit 2 Unix Kernel Level Services

The document provides an overview of UNIX kernel-level services and commands, focusing on process and memory management. It details key functions such as process creation, execution, and termination, along with relevant commands like ps, top, and free. Additionally, it discusses managing process priorities and handling high CPU usage scenarios, as well as monitoring memory usage with commands like vmstat and ulimit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views37 pages

UNit 2 Unix Kernel Level Services

The document provides an overview of UNIX kernel-level services and commands, focusing on process and memory management. It details key functions such as process creation, execution, and termination, along with relevant commands like ps, top, and free. Additionally, it discusses managing process priorities and handling high CPU usage scenarios, as well as monitoring memory usage with commands like vmstat and ulimit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIX Kernel-Level Services and Commands

The UNIX kernel is the core component of the operating system responsible for managing hardware
and system resources. It provides essential services such as process management, memory
management, file system handling, device management, and system calls.
Process management

Process Management

Handles process creation, scheduling, and termination.

● Key functions: Process creation (fork()), execution (exec()), termination (exit()), and scheduling.

Commands:

● ps - Displays currently running processes.


● top - Provides real-time system resource usage.
● kill <PID> - Terminates a process by its Process ID.
● nice / renice - Adjusts process priority.
● jobs - Lists background jobs.
● fg / bg - Moves jobs between foreground and background.
Process management

Executing Process Creation (fork())

The fork() function is used to create a new process in C

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

int main() {
pid_t pid = fork(); // Create a child process

if (pid > 0) {
printf("Parent process, PID: %d\n", getpid());
} else if (pid == 0) {
printf("Child process, PID: %d, Parent PID: %d\n", getpid(), getppid());
} else {
printf("Fork failed!\n");
}

return 0;
}
Process management

Compile and Run the Program

gcc fork_example.c -o fork_example

./fork_example

Output

Parent process, PID: 1234

Child process, PID: 1235, Parent PID: 1234


Executing Process Execution (exec())
The exec() function replaces the current process with a new one.

Step 1: Create a C program

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

int main() {
printf("Before exec()\n");
execlp("ls", "ls", "-l", NULL); // Execute 'ls -l' command
printf("This line will not execute if exec() succeeds\n");
return 0;
}
Executing Process Execution (exec())
Step 2: Compile and Run the Program

gcc exec_example.c -o exec_example


./exec_example

Output

Before exec()
total 12
-rw-r--r-- 1 user user 234 Feb 17 12:00 file1.txt
-rw-r--r-- 1 user user 456 Feb 17 12:05 file2.txt

If exec() is successful, the second printf() statement will not execute.


Executing Process Termination (exit())
Step 2: Compile and Run the Program
The exit() function terminates a process.

Step 1: Create a C program gcc exit_example.c -o exit_example

./exit_example

#include <stdio.h>

#include <stdlib.h>
Output

int main() {
Process is running...
printf("Process is running...\n");
The process terminates immediately after printing the
exit(0); // Terminate the process message.

}
Managing and Monitoring Processes

Built-in shell commands for process management.

View Running Processes (ps and top)

ps aux # Show all running processes


ps -ef # Show all processes with user details
top # Show real-time process details

Example Output of ps aux:

USER PID %CPU %MEM COMMAND


root 1234 5.3 2.1 apache2
user 5678 2.0 1.2 python3 script.py
Killing a Process
Find the process ID using:

ps aux | grep process_name

Terminate the process:

kill 1234 # (gentle kill)


kill -9 1234 # (force kill)
Adjusting Process Priority (nice and renice)
Start a process with a lower priority:

nice -n 10 my_program # Run process with priority 10

Change priority of an existing process:

renice -5 -p 1234 # Set priority to -5 for process 1234


Managing Background Jobs (jobs, fg, bg)
Run a command in the background:

sleep 60 & # Run sleep command in the background

List background jobs:

jobs

Move a job to the foreground:

fg %1 # Bring job 1 to the foreground

Resume a background job:

bg %1 # Resume job 1 in the background


Managing High CPU Usage Process

Scenario:

A system administrator notices that a process (python3 script.py) is consuming 90% CPU. The system performance is
degrading.

Problem Statement:

How can we reduce the CPU priority of a process without stopping it?
Steps to Solve:
Find the Process ID (PID) of python3 script.py:

ps aux | grep python3

Example Output:

user 4567 90.3 2.5 134256 4532 ? S 12:00 45:23 python3 script.py

Lower the priority:

renice 10 -p 4567
Terminating a Hung Process

Scenario:

A user’s terminal becomes unresponsive after running a poorly optimized program. The
process does not terminate normally.

Problem Statement:

How can we forcefully terminate an unresponsive process?

Solution:

Use kill or kill -9 to terminate the process.


Terminating a Hung Process

Steps to Solve:

Identify the PID:


ps aux | grep unresponsive_program

Example Output:

user 6789 100.0 1.2 102400 2048 ? R 12:10 10:12 unresponsive_program

Attempt to terminate gracefully:

kill 6789

If it does not respond, use a forceful kill:

kill -9 6789

Confirm termination:

ps aux | grep 6789

If the process no longer appears, it has been successfully terminated.


Running and Managing Background Jobs

Scenario:

A user runs a script that takes 10 minutes to complete but needs to continue working in the terminal.

Problem Statement:

How can the user continue using the terminal while keeping the process running?

Solution:

Run the script in the background and manage it using jobs, fg, and bg.
Steps to Solve:

Run the script in the background:


./long_running_script.sh &

Example Output:
[1] 12345

Here, [1] is the job number, and 12345 is the PID.

Check running background jobs:


jobs

Example Output:

[1]+ Running ./long_running_script.sh &

Bring the process to the foreground:

fg %1

Send it back to the background:

bg %1
Memory Management

Memory management in Linux is a crucial aspect of system performance monitoring. The


following commands help analyze and manage memory usage effectively.

Commands:

● free - Displays available and used memory.


● vmstat - Reports memory, CPU, and disk I/O statistics.
● top - Shows real-time memory usage.
● ulimit - Sets memory usage limits for users.
Memory Management

free - Displays Available and Used Memory


The free command provides information about total, used, and available memory, including swap memory.

Usage:

free -h

Output:

total used free shared buff/cache available

Mem: 7.7Gi 4.2Gi 1.1Gi 512Mi 2.4Gi 2.8Gi

Swap: 2.0Gi 500Mi 1.5Gi


Memory Management
● total: Total physical memory.
● used: Memory currently in use.
● free: Unused memory.
● shared: Memory shared between processes.
● buff/cache: Memory used for buffering and caching.
● available: Memory available for new processes.

Additional Options:
● free -m → Show output in MB.
● free -g → Show output in GB.
● free -t → Display total memory, including swap.
Memory Management

vmstat - Reports Memory, CPU, and Disk I/O Statistics


The vmstat (Virtual Memory Statistics) command provides a summary of memory usage, system performance, and disk I/O.

Output:

procs -----------memory---------- ---swap-- -----io---- --system-- ------cpu-----

r b swpd free buff cache si so bi bo in cs us sy id wa st

1 0 0 85732 32456 127456 0 0 3 5 2 7 5 2 92 1 0

0 0 0 85564 32456 127456 0 0 0 1 150 300 3 1 96 0 0


● cpu (us, sy, id, wa, st):
Memory Management ○ us: CPU usage by user
● procs (r, b): Number of running (r) and blocked (b) processes.
processes. ○ sy: CPU usage by
● memory (swpd, free, buff, cache): system processes.
○ swpd: Swap memory used. ○ id: Idle CPU.
○ free: Free memory. ○ wa: CPU waiting for I/O.
○ buff: Memory used for buffers. ○ st: CPU stolen by virtual
○ cache: Memory used for disk cache. machines.
● swap (si, so):
Additional Options:
○ si: Swap memory in.
○ so: Swap memory out. ● vmstat -s → Show memory
● io (bi, bo): statistics.
○ bi: Blocks received from disk. ● vmstat -d → Show disk
○ bo: Blocks sent to disk. statistics.
top - Shows Real-Time Memory Usage
The top command provides a dynamic real-time view of system resource usage, including CPU, memory, and running processes.

Output (Partial View):

top - 12:34:56 up 3:45, 1 user, load average: 0.50, 0.75, 0.60


Tasks: 152 total, 2 running, 150 sleeping, 0 stopped, 0 zombie
%Cpu(s): 5.2 us, 1.3 sy, 0.0 ni, 93.1 id, 0.2 wa, 0.0 hi, 0.2 si, 0.0 st
KiB Mem : 8077620 total, 3467620 free, 2100256 used, 2509744 buff/cache
KiB Swap: 2097152 total, 1509920 free, 587232 used. 4872396 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND


2034 user 20 0 537384 32560 9404 S 2.3 0.4 0:12.56 gnome-terminal
1758 root 20 0 371276 28744 8208 S 1.7 0.3 0:10.25 Xorg
Header Information:

● load average: Average CPU load over 1, 5, and 15 minutes.


● Tasks: Number of total, running, sleeping, and zombie processes.
● CPU usage: Breakdown of CPU usage by user, system, idle, etc.
● Memory (Mem, Swap): Displays physical and swap memory usage.

Process Table (Columns):

● PID: Process ID.


● USER: User who owns the process.
● PR: Priority.
● NI: Nice value (priority adjustment).
● VIRT: Virtual memory used.
● RES: Resident memory used.
● %CPU, %MEM: CPU and memory usage percentage.
● COMMAND: Name of the running command.
ulimit - Sets Memory Usage Limits for Users
The ulimit command restricts the resources available to processes running in a shell session.

Usage:

Explanation:
ulimit -a
● -m: Maximum memory a process can use.
● -u: Maximum number of user processes.
Output: ● -n: Maximum number of open file descriptors.
java
CopyEdit Set Memory Limits for a Process
core file size (blocks, -c) unlimited
data seg size (kbytes, -d) unlimited ulimit -m 1048576 # Limit memory to 1GB (1024 *
scheduling priority (-e) 0 1024 KB)
file size (blocks, -f) unlimited ulimit -n 2048 # Allow up to 2048 open files
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
max user processes (-u) 4096
Key Differences Between User Process and System Process

Feature User Process System Process

Started by User (via terminal, GUI, or script) System (during boot or as a


service)

Examples Firefox, Gedit, Python scripts systemd, cron, sshd, mysqld

Runs in Foreground/Background Background (Daemon)

Can be killed by Yes, using kill Some require sudo to kill


user?

Command to check `ps aux grep <process_name>`


Scenario:

A system administrator notices that the system is slowing down significantly. Applications are
lagging, and there are frequent system hangs. The administrator suspects high memory
usage.

Problem Statement:

How can the administrator determine if the system is running low on memory and identify the
available free memory?

Solution:

Use the free command to check memory usage.


free -h

Output:

total used free shared buff/cache available

Mem: 16Gi 14Gi 500Mi 800Mi 1.5Gi 1.2Gi

Swap: 4.0Gi 3.5Gi 500Mi

Analysis:

● The total memory is 16GB, but 14GB is used.


● Only 500MB of free memory is left.
● The swap memory usage is high (3.5GB out of 4GB), indicating that the system is using swap due to
insufficient RAM.

Resolution:

1. Close unnecessary applications consuming memory.


2. Increase swap space using the following command:
A cloud-based server running a web application is experiencing performance degradation, especially
during peak traffic hours.

Problem Statement:

How can the administrator monitor memory usage along with CPU and I/O statistics to detect any
bottlenecks?

Solution:

Use the vmstat command to analyze memory usage, CPU load, and disk I/O.
vmstat

procs -----------memory---------- ---swap-- -----io---- --system-- ------cpu-----

r b swpd free buff cache si so bi bo in cs us sy id wa st

1 0 0 102400 34560 128000 0 0 5 10 200 500 5 3 90 2 0

2 0 1024 98700 34000 129000 5 2 10 20 210 550 8 5 85 2 0

Analysis:

● Memory Section (swpd, free, buff, cache):


○ free: Only 102400 KB (~100MB) free, indicating high memory usage.
○ swpd: Swap usage is increasing (1024 KB → 98700 KB), meaning RAM is full.
● CPU Section (us, sy, id, wa):
○ us: User CPU utilization is 8%, which is normal.
○ wa: CPU wait time is 2%, which is acceptable.
○ id: CPU idle time is 85%, meaning the CPU is not overloaded.

Resolution:

1. Increase server RAM if demand is constant.


2. Optimize database queries to reduce memory consumption.
Scenario:

A user reports that their laptop is running very slowly, with frequent freezing. They suspect an application is
using too much memory.

Problem Statement:

How can the user identify and terminate the process consuming excessive memory?

Solution:

Use the top command to find the process with the highest memory usage and kill it.
top

Output (Partial View):

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

3456 user 20 0 2500M 1600M 900M R 2.3 40.0 1:23.45 chrome

1234 user 20 0 800M 600M 400M S 1.5 20.0 0:45.30 firefox

Analysis:

● Google Chrome (PID 3456) is using 1.6GB of RAM (40%).


● Firefox (PID 1234) is using 600MB of RAM (20%).
● Chrome is the biggest memory consumer, causing system lag.

Resolution:

Kill Chrome to free up memory:


kill 3456

If it does not close, force kill:


kill -9 3456
top

Output (Partial View):

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

3456 user 20 0 2500M 1600M 900M R 2.3 40.0 1:23.45 chrome

1234 user 20 0 800M 600M 400M S 1.5 20.0 0:45.30 firefox

Analysis:

● Google Chrome (PID 3456) is using 1.6GB of RAM (40%).


● Firefox (PID 1234) is using 600MB of RAM (20%).
● Chrome is the biggest memory consumer, causing system lag.

Resolution:

Kill Chrome to free up memory:


kill 3456

If it does not close, force kill:


kill -9 3456
Scenario:

A shared Linux server is being used by multiple developers. One of them runs a script that consumes
excessive memory, affecting other users.

Problem Statement:

How can the administrator limit memory usage for individual users to prevent a single user from consuming
too much RAM?

Solution:

Use the ulimit command to restrict memory usage for a user.


Check current memory limits:

ulimit -a
Output:

max memory size (kbytes, -m) unlimited


open files (-n) 1024
max user processes (-u) 4096

Issue: The memory limit is currently unlimited, meaning a single process can use all available memory.

Set a memory limit of 2GB (2048000 KB) for user sessions:

ulimit -m 2048000

Verify the new limit:

ulimit -m

Output:

2048000
File System Management

Controls file access, storage, and permissions.

● Key functions: File creation, deletion, access control, and mounting.

Commands:

● ls - Lists files and directories.


● chmod - Changes file permissions.
● chown - Changes file ownership.
● df - Displays disk space usage.
● du - Shows directory space usage.
● mount / umount - Mounts and unmounts file systems.
● fsck - Checks and repairs the file system.
Feature Kernel-Level Services System-Level Services

Definition Core services of the OS that directly interact Services running on top of the kernel to
with hardware provide system functionality

Managed By Kernel System daemons, user commands

Functionality Process management, memory Networking, logging, scheduling,


management, device control, IPC, security authentication, user process management

Example Process scheduling, memory paging, file SSH, FTP, logging, web servers, firewall, cron
Services
system operations, device drivers jobs

Example ps, kill, df, free, mount systemctl, crontab, netstat, tail -f
Commands /var/log/syslog

When Used? When interacting with hardware or system When running system services, applications,
resources and networking tools

You might also like