
Practical 3: Implementation of CPU scheduling algorithm (FCFS)   Q: Implement First Come First Serve (FCFS) CPU scheduling algorithm with dynamic user input?   Working:Takes the number of processes, process names/IDs, Arrival Times ($AT$), and Burst Times ($BT$) from the user.   Sorts processes based on $AT$.   For each process:$\text{Completion Time }(CT) = \max(\text{current\_time}, AT) + BT$$\text{Turnaround Time }(TAT) = CT - AT$$\text{Waiting Time }(WT) = TAT - BT$Calculates and prints individual and average $TAT$ and $WT$.Input Required:Number of processes: 3Process 1: P1, Arrival Time: 0, Burst Time: 4Process 2: P2, Arrival Time: 1, Burst Time: 3Process 3: P3, Arrival Time: 2, Burst Time: 1Code:Pythondef main():
    n = int(input("Enter number of processes: "))
    proc = []
    for _ in range(n):
        pid = input("Process ID/Name: ")
        at = int(input(f"Enter Arrival Time for {pid}: "))
        bt = int(input(f"Enter Burst Time for {pid}: "))
        proc.append([pid, at, bt])

    proc.sort(key=lambda x: x[1])

    ct, tat, wt = [0] * n, [0] * n, [0] * n
    curr_time = 0

    for i in range(n):
        if curr_time < proc[i][1]:
            curr_time = proc[i][1]
        curr_time += proc[i][2]
        ct[i] = curr_time
        tat[i] = ct[i] - proc[i][1]
        wt[i] = tat[i] - proc[i][2]

    print("\nPID\tAT\tBT\tCT\tTAT\tWT")
    for i in range(n):
        print(f"{proc[i][0]}\t{proc[i][1]}\t{proc[i][2]}\t{ct[i]}\t{tat[i]}\t{wt[i]}")

    print(f"\nAverage TAT = {sum(tat)/n:.2f}")
    print(f"Average WT  = {sum(wt)/n:.2f}")

if __name__ == "__main__":
    main()
Output:PlaintextEnter number of processes: 3
Process ID/Name: P1
Enter Arrival Time for P1: 0
Enter Burst Time for P1: 4
Process ID/Name: P2
Enter Arrival Time for P2: 1
Enter Burst Time for P2: 3
Process ID/Name: P3
Enter Arrival Time for P3: 2
Enter Burst Time for P3: 1

PID	AT	BT	CT	TAT	WT
P1	0	4	4	4	0
P2	1	3	7	6	3
P3	2	1	8	6	5

Average TAT = 5.33
Average WT  = 2.67



Practical 4: Implementation of CPU scheduling algorithm (SJF - Non-Preemptive)   Q: Implement Shortest Job First (Non-Preemptive) CPU scheduling algorithm with dynamic user input?   Working:Takes the number of processes, $AT$, and $BT$ from the user.   Tracks current time and completed processes.Among processes that have arrived ($AT \le \text{current\_time}$) and are uncompleted, selects the one with the minimum $BT$.Computes $CT$, $TAT = CT - AT$, and $WT = TAT - BT$.Advances time and repeats until all processes finish.Input Required:Number of processes: 4Process 1: P1, Arrival Time: 0, Burst Time: 7Process 2: P2, Arrival Time: 2, Burst Time: 4Process 3: P3, Arrival Time: 4, Burst Time: 1Process 4: P4, Arrival Time: 5, Burst Time: 4Code:Pythondef main():
    n = int(input("Enter number of processes: "))
    proc = []
    for _ in range(n):
        pid = input("Process ID/Name: ")
        at = int(input(f"Enter Arrival Time for {pid}: "))
        bt = int(input(f"Enter Burst Time for {pid}: "))
        proc.append([pid, at, bt])

    completed = [False] * n
    ct, tat, wt = [0] * n, [0] * n, [0] * n
    curr_time = 0
    completed_count = 0

    while completed_count < n:
        idx = -1
        min_bt = float('inf')
        for i in range(n):
            if proc[i][1] <= curr_time and not completed[i]:
                if proc[i][2] < min_bt:
                    min_bt = proc[i][2]
                    idx = i

        if idx != -1:
            curr_time += proc[idx][2]
            ct[idx] = curr_time
            tat[idx] = ct[idx] - proc[idx][1]
            wt[idx] = tat[idx] - proc[idx][2]
            completed[idx] = True
            completed_count += 1
        else:
            curr_time += 1

    print("\nPID\tAT\tBT\tCT\tTAT\tWT")
    for i in range(n):
        print(f"{proc[i][0]}\t{proc[i][1]}\t{proc[i][2]}\t{ct[i]}\t{tat[i]}\t{wt[i]}")

    print(f"\nAverage TAT = {sum(tat)/n:.2f}")
    print(f"Average WT  = {sum(wt)/n:.2f}")

if __name__ == "__main__":
    main()
Output:PlaintextEnter number of processes: 4
Process ID/Name: P1
Enter Arrival Time for P1: 0
Enter Burst Time for P1: 7
Process ID/Name: P2
Enter Arrival Time for P2: 2
Enter Burst Time for P2: 4
Process ID/Name: P3
Enter Arrival Time for P3: 4
Enter Burst Time for P3: 1
Process ID/Name: P4
Enter Arrival Time for P4: 5
Enter Burst Time for P4: 4

PID	AT	BT	CT	TAT	WT
P1	0	7	7	7	0
P2	2	4	12	10	6
P3	4	1	8	4	3
P4	5	4	16	11	7

Average TAT = 8.00
Average WT  = 4.00


Practical 5: Implementation of CPU scheduling algorithm (Round Robin)   Q: Implement Round Robin CPU scheduling algorithm with dynamic time quantum and burst times?   Working:Takes number of processes, process names, burst times, and a time quantum from the user.   Cycles through processes, allocating the CPU up to the time quantum.Deducts executed time from remaining burst time until remaining time reaches 0.Computes $CT$, $TAT = CT$, and $WT = TAT - BT$.Input Required:Number of processes: 3Process 1: P1, Burst Time: 8Process 2: P2, Burst Time: 5Process 3: P3, Burst Time: 10Time quantum: 2Code:Pythondef main():
    n = int(input("Enter number of processes: "))
    pids = []
    bt = []
    for _ in range(n):
        pids.append(input("Process ID/Name: "))
        bt.append(int(input(f"Enter Burst Time for {pids[-1]}: ")))
    quantum = int(input("Enter Time Quantum: "))

    rem_bt = bt.copy()
    ct = [0] * n
    curr_time = 0

    while True:
        done = True
        for i in range(n):
            if rem_bt[i] > 0:
                done = False
                if rem_bt[i] > quantum:
                    curr_time += quantum
                    rem_bt[i] -= quantum
                else:
                    curr_time += rem_bt[i]
                    ct[i] = curr_time
                    rem_bt[i] = 0
        if done:
            break

    tat = [ct[i] for i in range(n)]
    wt = [tat[i] - bt[i] for i in range(n)]

    print("\nPID\tBT\tCT\tTAT\tWT")
    for i in range(n):
        print(f"{pids[i]}\t{bt[i]}\t{ct[i]}\t{tat[i]}\t{wt[i]}")

    print(f"\nAverage TAT = {sum(tat)/n:.2f}")
    print(f"Average WT  = {sum(wt)/n:.2f}")

if __name__ == "__main__":
    main()
Output:PlaintextEnter number of processes: 3
Process ID/Name: P1
Enter Burst Time for P1: 8
Process ID/Name: P2
Enter Burst Time for P2: 5
Process ID/Name: P3
Enter Burst Time for P3: 10
Enter Time Quantum: 2

PID	BT	CT	TAT	WT
P1	8	19	19	11
P2	5	13	13	8
P3	10	23	23	13

Average TAT = 18.33
Average WT  = 10.67




Practical 6: Implementation of Banker's Algorithm for Deadlock Avoidance   Q: Implement Banker's Algorithm to check system safety and output the safe sequence?   Working:Accepts processes count, resources count, Allocation matrix, Max matrix, and Available vector.   Computes the Need matrix: $\text{Need}[i][j] = \text{Max}[i][j] - \text{Allocation}[i][j]$.   Finds an unallocated process whose need can be satisfied by currently available resources.Simulates resource return when process finishes and appends process ID to the safe sequence list.Confirms state safety if all processes execute safely.   Input Required:Number of processes: 3Number of resources: 2Allocation for P0: 1 0, Max for P0: 2 1Allocation for P1: 2 1, Max for P1: 3 2Allocation for P2: 0 1, Max for P2: 1 2Available resources: 1 1Code:Pythondef main():
    n = int(input("Enter number of processes: "))
    m = int(input("Enter number of resource types: "))

    print("\nEnter Allocation Matrix row by row:")
    alloc = [list(map(int, input(f"P{i}: ").split())) for i in range(n)]

    print("\nEnter Max Demand Matrix row by row:")
    max_d = [list(map(int, input(f"P{i}: ").split())) for i in range(n)]

    avail = list(map(int, input("\nEnter Available Resources vector: ").split()))

    need = [[max_d[i][j] - alloc[i][j] for j in range(m)] for i in range(n)]
    finish = [False] * n
    safe_seq = []
    work = avail.copy()

    while len(safe_seq) < n:
        found = False
        for i in range(n):
            if not finish[i] and all(need[i][j] <= work[j] for j in range(m)):
                for j in range(m):
                    work[j] += alloc[i][j]
                finish[i] = True
                safe_seq.append(f"P{i}")
                found = True
                break
        if not found:
            break

    if len(safe_seq) == n:
        print("\nSystem is in a SAFE state.")
        print("Safe sequence:", " -> ".join(safe_seq))
    else:
        print("\nSystem is in an UNSAFE state (Deadlock may occur).")

if __name__ == "__main__":
    main()
Output:PlaintextEnter number of processes: 3
Enter number of resource types: 2

Enter Allocation Matrix row by row:
P0: 1 0
P1: 2 1
P2: 0 1

Enter Max Demand Matrix row by row:
P0: 2 1
P1: 3 2
P2: 1 2

Enter Available Resources vector: 1 1

System is in a SAFE state.
Safe sequence: P0 -> P1 -> P2



Practical 7: Fixed Partition Memory Allocation (First Fit, Best Fit, Worst Fit)   Q: Implement First Fit, Best Fit, and Worst Fit algorithms with user-defined partitions and processes?   Working:Accepts block sizes and process sizes from the user.   First Fit: Allocates the process into the first block with sufficient capacity.   Best Fit: Allocates the process into the smallest block that fits it.   Worst Fit: Allocates the process into the largest block available.   Subtracts the allocated process size from the block size for subsequent allocations.Input Required:Block sizes: 100 500 200 300 600Process sizes: 212 417 112 426Code:Pythondef first_fit(blocks, procs):
    b = blocks.copy()
    alloc = [-1] * len(procs)
    for i, p in enumerate(procs):
        for j in range(len(b)):
            if b[j] >= p:
                alloc[i] = j
                b[j] -= p
                break
    return alloc

def best_fit(blocks, procs):
    b = blocks.copy()
    alloc = [-1] * len(procs)
    for i, p in enumerate(procs):
        best_idx = -1
        for j in range(len(b)):
            if b[j] >= p and (best_idx == -1 or b[j] < b[best_idx]):
                best_idx = j
        if best_idx != -1:
            alloc[i] = best_idx
            b[best_idx] -= p
    return alloc

def worst_fit(blocks, procs):
    b = blocks.copy()
    alloc = [-1] * len(procs)
    for i, p in enumerate(procs):
        worst_idx = -1
        for j in range(len(b)):
            if b[j] >= p and (worst_idx == -1 or b[j] > b[worst_idx]):
                worst_idx = j
        if worst_idx != -1:
            alloc[i] = worst_idx
            b[worst_idx] -= p
    return alloc

def main():
    blocks = list(map(int, input("Enter memory block sizes (space-separated): ").split()))
    procs = list(map(int, input("Enter process memory sizes (space-separated): ").split()))

    print("\n--- Allocation Results (Block Index allocated to Process) ---")
    print("First Fit Allocation:", first_fit(blocks, procs))
    print("Best Fit Allocation :", best_fit(blocks, procs))
    print("Worst Fit Allocation:", worst_fit(blocks, procs))

if __name__ == "__main__":
    main()
Output:PlaintextEnter memory block sizes (space-separated): 100 500 200 300 600
Enter process memory sizes (space-separated): 212 417 112 426

--- Allocation Results (Block Index allocated to Process) ---
First Fit Allocation: [1, 4, 1, -1]
Best Fit Allocation : [3, 1, 2, 4]
Worst Fit Allocation: [4, 1, 3, -1]
Practical 8: Implementation of Page Replacement Algorithms (FIFO & LRU)   Q: Implement FIFO and LRU page replacement policies and count page faults from user input?   Working:Accepts reference string (pages sequence) and frame capacity from the user.   FIFO: If a page is not in memory and capacity is reached, removes the first (earliest inserted) item.   LRU: If a page is not in memory and capacity is reached, removes the least recently accessed item. If already present (hit), repositions it to the most recently used end.   Input Required:Reference string: 7 0 1 2 0 3 0 4 2 3Frame capacity: 3Code:Pythondef fifo(pages, capacity):
    memory = []
    faults = 0
    for p in pages:
        if p not in memory:
            if len(memory) == capacity:
                memory.pop(0)
            memory.append(p)
            faults += 1
    return faults

def lru(pages, capacity):
    memory = []
    faults = 0
    for p in pages:
        if p not in memory:
            if len(memory) == capacity:
                memory.pop(0)
            memory.append(p)
            faults += 1
        else:
            memory.remove(p)
            memory.append(p)
    return faults

def main():
    pages = list(map(int, input("Enter reference string (space-separated): ").split()))
    capacity = int(input("Enter frame capacity: "))

    print(f"\nTotal Page Faults (FIFO): {fifo(pages, capacity)}")
    print(f"Total Page Faults (LRU) : {lru(pages, capacity)}")

if __name__ == "__main__":
    main()
Output:PlaintextEnter reference string (space-separated): 7 0 1 2 0 3 0 4 2 3
Enter frame capacity: 3

Total Page Faults (FIFO): 9
Total Page Faults (LRU) : 8



Practical 9: File System Operations (Create, Read, Write, Delete, Rename)   Q: Implement complete interactive file system operations (write, read, rename, delete) using user inputs?   Working:Takes the file name and content text directly from the user.   Writes content to file using open(..., 'w').   Reads and prints file content back using open(..., 'r').   Prompts for a new file name and uses os.rename() to update the disk reference.   Uses os.remove() to delete the file.   Input Required:File name: testfile.txtContent: Operating System Lab WorkNew file name: renamed_file.txtCode:Pythonimport os

def main():
    filename = input("Enter filename to create: ")
    content = input("Enter text content to write: ")

    # 1. Create and Write
    with open(filename, "w") as f:
        f.write(content)
    print(f"[Success] Created and wrote data to '{filename}'")

    # 2. Read
    with open(filename, "r") as f:
        print(f"[Read Content] '{filename}': {f.read()}")

    # 3. Rename
    new_filename = input("Enter new filename to rename: ")
    if os.path.exists(filename):
        os.rename(filename, new_filename)
        print(f"[Success] Renamed '{filename}' to '{new_filename}'")

    # 4. Delete
    if os.path.exists(new_filename):
        os.remove(new_filename)
        print(f"[Success] Deleted '{new_filename}'")

if __name__ == "__main__":
    main()
Output:PlaintextEnter filename to create: testfile.txt
Enter text content to write: Operating System Lab Work
[Success] Created and wrote data to 'testfile.txt'
[Read Content] 'testfile.txt': Operating System Lab Work
Enter new filename to rename: renamed_file.txt
[Success] Renamed 'testfile.txt' to 'renamed_file.txt'
[Success] Deleted 'renamed_file.txt'


---------------------------------------------------------------------------------------------------------------------------------------

PRAC 1 and 2




How to Run C Programs in Ubuntu TerminalOpen Terminal (Ctrl + Alt + T).Create/open the C file using nano or gedit:Bashnano prac2.c
Paste the code, save, and exit (Ctrl + O then Enter, then Ctrl + X in nano).Compile using GCC:Bashgcc prac2.c -o prac2
Run the executable:Bash./prac2
Practical 1: Study and execution of basic Linux/UNIX shell commandsQ: Demonstrate basic Linux/UNIX commands in terminal and via C program using system()?   Working:Linux shell commands (pwd, ls, whoami, date, uname) are executed directly in the bash terminal.   In C, the system() function from <stdlib.h> passes command strings directly to the Linux shell (/bin/sh) for execution.   Input Required:NACode (prac1.c):C#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("--- 1. Print Working Directory ---\n");
    system("pwd");

    printf("\n--- 2. Current User ---\n");
    system("whoami");

    printf("\n--- 3. System Date & Time ---\n");
    system("date");

    printf("\n--- 4. Kernel Information ---\n");
    system("uname -r");

    printf("\n--- 5. List Files ---\n");
    system("ls -l");

    return 0;
}
Output:Plaintext--- 1. Print Working Directory ---
/home/student/os_lab

--- 2. Current User ---
student

--- 3. System Date & Time ---
Tue Nov 03 17:15:00 IST 2026

--- 4. Kernel Information ---
6.8.0-generic

--- 5. List Files ---
total 24
-rw-r--r-- 1 student student  412 Nov  3 17:10 prac1.c
-rwxr-xr-x 1 student student 16080 Nov  3 17:12 prac1
-rw-r--r-- 1 student student  530 Nov  3 17:14 prac2.c



Practical 2: Program to create and terminate processes using system callsQ: Create child process using fork(), print child/parent PIDs using getpid()/getppid(), wait for completion using wait(), and terminate using exit()?   Working:fork() spawns a duplicate child process.   Return value < 0: Fork failed.   Return value == 0: Inside the child process; getpid() displays child PID, getppid() displays parent PID.   Return value > 0: Inside parent process; holds the child PID.   wait(NULL) blocks the parent until the child process terminates, preventing a zombie process.   exit(0) terminates the child process cleanly.   Input Required:NACode (prac2.c):C

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

int main() {
    pid_t pid;

    pid = fork();

    if (pid < 0) {
        printf("Fork failed\n");
        return 1;
    } else if (pid == 0) {
        printf("[Child Process]\n");
        printf("Child PID  = %d\n", getpid());
        printf("Parent PID = %d\n", getppid());
        printf("Child process terminating...\n");
        exit(0);
    } else {
        printf("[Parent Process]\n");
        printf("Parent PID = %d\n", getpid());
        printf("Waiting for child process to finish...\n");
        wait(NULL);
        printf("Child process has terminated.\n");
    }

    return 0;
}
Output:Plaintext[Parent Process]
Parent PID = 14205
Waiting for child process to finish...
[Child Process]
Child PID  = 14206
Parent PID = 14205
Child process terminating...
Child process has terminated.





