0% found this document useful (0 votes)
13 views45 pages

CS Practical

The document contains various Linux command executions and programming tasks related to process control, memory management, file handling, and scheduling algorithms. It includes explanations and code examples for commands like 'ps', 'kill', 'chmod', and programming tasks implementing scheduling algorithms such as FCFS, SJF, and non-preemptive priority-based scheduling. Additionally, it covers memory reporting and file copying using system calls.

Uploaded by

S.pvimal Pratap
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)
13 views45 pages

CS Practical

The document contains various Linux command executions and programming tasks related to process control, memory management, file handling, and scheduling algorithms. It includes explanations and code examples for commands like 'ps', 'kill', 'chmod', and programming tasks implementing scheduling algorithms such as FCFS, SJF, and non-preemptive priority-based scheduling. Additionally, it covers memory reporting and file copying using system calls.

Uploaded by

S.pvimal Pratap
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/ 45

Name:Ashwani nigam

roll-no:0407
c.s practical
question 1:Execute various LINUX commands for

(i) Information Maintenance: wc, clear, cal, who, date, pwd

(ii) File Management: cat, cp, rm, mv, cmp, comm, diff, find, grep, awk

(iii) Directory Management: cd, mkdir, rmdir, ls

ANS:Information Maintenance

wc : Displays line, word, and character counts of the file

clear: Clears all previous output from the terminal

cal: Displays the current month’s calendar

pwd: Print working directory

File Management

cat: Concatenate and display file contents

rm: Remove files

mv: Move or rename files

cmp: Compare two files byte by byte

comm: Compare two sorted files line by line

diff: Show line-by-line differences between files

Command:

find: Locate files in a directory


grep: Search for patterns in files

awk: Text processing and pattern matching

Directory Management Commands

cd: Change directory

mkdir: Create a new directory

rmdir: Remove an empty directory

ls: List directory contents


QUESTION 2: Execute various LINUX commands for:

Process Control

ps

The ps command shows the current processes running on the system.


Example:

ps-aux

killfork()

#include <stdio.h>

#include <unistd.h>

int main() {

pid_t pid = fork();

if (pid == 0) {

printf("Child process with PID: %d\n", getpid());

} else if (pid > 0) {

printf("Parent process with PID: %d\n", getpid());

} else {

perror("Fork failed");

return 0;

getpid

#include <stdio.h>

#include <unistd.h>

int main() {
printf("Current process ID is: %d\n", getpid());

return 0;

The kill command sends a signal to a process. By default, it sends the SIGTERM signal,

which requests termination of the process.

Example:

kill 1234 # Terminate process with PID 1234

sleep

The sleep command pauses the execution for a specified number of seconds.

Example:

sleep 5 # Sleep for 5 seconds

Communication:

1. Input-Output Redirection

Standard Output Redirection (>) Redirect the output of a command to a file.

Example:

echo "Hello World" > output.txt

This will write "Hello World" to output.txt.

Standard Input Redirection (<) Redirect input from a file to a command.

Example:

sort < input.txt


This will sort the contents of input.txt and display the result.

AppendOutput (>>) Append output to an existing file.

Example:

echo "New Line" >> output.txt

2. Pipe()

Pipes allow the output of one command to be used as the input for another command.

Example:

ps-aux | grep "python"

This will list all processes, then filter for processes containing the word "python."

Protection Management

1. chmod

The chmod command changes the permissions of a file or directory.

Example:

chmod 755 myfile.txt # rwx for owner, rx for group and others

chmod u+x myfile.sh # Add execute permission for the user

chmod o-r myfile.txt # Remove read permission for others

2. chown

The chown command changes the owner and/or group of a file.

Example:
chown user:group myfile.txt

chown user myfile.txt

3. chgrp (Change Group Ownership)

The chgrp command changes the group ownership of a file.

Example:

chgrp admin myfile.txt # Change the group to 'admin

QUESTION 3.Write a program (using fork() and/or exec() commands) were parent and
child execute

(i) same program same code

#include <stdio.h>

#include <unistd.h>

int main() {

pid_t pid = fork(); // Create a new process

if (pid == 0) {

// Child process

printf("Child: Executing same program, same code\n");

} else if (pid > 0) {

// Parent process

printf("Parent: Executing same program, same code\n");


} else {

perror("Fork failed");

return 0;

(ii) same program different code

#include <stdio.h>

#include <unistd.h>

int main() {

pid_t pid = fork(); // Create a new process

if (pid == 0) {

// Child process

printf("Child: Executing child-specific code\n");

} else if (pid > 0) {

// Parent process

printf("Parent: Executing parent-specific code\n");

} else {

perror("Fork failed");

return 0;
}

(iii) before terminating the parent waits for the child to finish its task

#include <stdio.h>

#include <unistd.h>

#include <sys/wait.h>

int main() {

pid_t pid = fork(); // Create a new process

if (pid == 0) {

// Child process

printf("Child: Doing some task...\n");

sleep(2); // Simulate work

printf("Child: Task completed\n");

} else if (pid > 0) {

// Parent process

printf("Parent: Waiting for child to finish...\n");

wait(NULL); // Wait for child to complete

printf("Parent: Child has finished. Exiting.\n");

} else {

perror("Fork failed");

}
return 0;

QUESTION4. Write a program to report behaviour of Linux kernel including kernel version
CPU type and CPU information.
QUESTION 5: Write a program to report behaviour of Linux kernel including information o
configured memory amount of free and used memory.

#include <stdio.h>

#include <stdlib.h>

void report_memory_info() {

FILE *file = fopen("/proc/meminfo", "r");

if (file == NULL) {

perror("Failed to open /proc/meminfo");

exit(EXIT_FAILURE);

}
char line[256];

unsigned long total_memory = 0, free_memory = 0, available_memory = 0;

// Read the file line by line and extract the memory details

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

if (sscanf(line, "MemTotal: %lu kB", &total_memory) == 1) {

continue;

if (sscanf(line, "MemFree: %lu kB", &free_memory) == 1) {

continue;

if (sscanf(line, "MemAvailable: %lu kB", &available_memory) == 1) {

break;

fclose(file);

// Calculate used memory

unsigned long used_memory = total_memory - available_memory;

// Print the memory report


printf("System Memory Report\n");

printf("----------------------------\n");

printf("Total Memory: %.2f MB\n", total_memory / 1024.0);

printf("Available Memory: %.2f MB\n", available_memory / 1024.0);

printf("Used Memory: %.2f MB\n", used_memory / 1024.0);

printf("Free Memory: %.2f MB\n", free_memory / 1024.0);

printf("----------------------------\n");

int main() {

report_memory_info();

return 0;

QUESTION 6: Write a program to copy files using system calls

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>
#include <errno.h>

#include <string.h>

#define BUFFER_SIZE 4096 // Size of the buffer for reading

void copy_file(const char *source, const char *destination) {

int source_fd, dest_fd;

ssize_t bytes_read, bytes_written;

char buffer[BUFFER_SIZE];

// Open the source file for reading

source_fd = open(source, O_RDONLY);

if (source_fd < 0) {

perror("Error opening source file");

return;

// Open the destination file for writing (create it if it doesn't exist)

dest_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (dest_fd < 0) {

perror("Error opening destination file");

close(source_fd);
return;

// Copy the contents from source to destination

while ((bytes_read = read(source_fd, buffer, BUFFER_SIZE)) > 0) {

bytes_written = write(dest_fd, buffer, bytes_read);

if (bytes_written != bytes_read) {

perror("Error writing to destination file");

close(source_fd);

close(dest_fd);

return;

if (bytes_read < 0) {

perror("Error reading from source file");

// Close the files

close(source_fd);

close(dest_fd);
if (bytes_read >= 0) {

printf("File copied successfully from '%s' to '%s'.\n", source, destination);

int main(int argc, char *argv[]) {

if (argc != 3) {

fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]);

return 1;

const char *source = argv[1];

const char *destination = argv[2];

copy_file(source, destination);

return 0;

QUESTION 7: Write a program to implement FCFS scheduling algorithm.

#include <stdio.h>
typedef struct {

int processID; // Process ID

int arrivalTime; // Arrival time

int burstTime; // Burst time

int completionTime; // Completion time

int turnAroundTime; // Turnaround time

int waitingTime; // Waiting time

} Process;

int main() {

int n, i;

Process processes[10];

printf("Enter the number of processes: ");

scanf("%d", &n);

for (i = 0; i < n; i++) {

processes[i].processID = i + 1;

printf("Enter arrival time and burst time for process %d: ", i + 1);

scanf("%d %d", &processes[i].arrivalTime, &processes[i].burstTime);

int currentTime = 0;
for (i = 0; i < n; i++) {

if (currentTime < processes[i].arrivalTime) {

currentTime = processes[i].arrivalTime;

processes[i].completionTime = currentTime + processes[i].burstTime;

processes[i].turnAroundTime = processes[i].completionTime - processes[i].arrivalTim

processes[i].waitingTime = processes[i].turnAroundTime - processes[i].burstTime;

currentTime = processes[i].completionTime;

// Corrected printf statement

printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\


tWaiting Time\n");

for (i = 0; i < n; i++) {

printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",

processes[i].processID,

processes[i].arrivalTime,

processes[i].burstTime,

processes[i].completionTime,

processes[i].turnAroundTime,

processes[i].waitingTime);

}
float totalTAT = 0, totalWT = 0;

for (i = 0; i < n; i++) {

totalTAT += processes[i].turnAroundTime;

totalWT += processes[i].waitingTime;

printf("\nAverage Turnaround Time: %.2f\n", totalTAT / n);

printf("Average Waiting Time: %.2f\n", totalWT / n);

return 0;

QUESTION 8: Write a program to SJF scheduling algorithm

#include <stdio.h>

typedef struct {
int processID; // Process ID

int arrivalTime; // Arrival time

int burstTime; // Burst time

int completionTime; // Completion time

int turnAroundTime; // Turnaround time

int waitingTime; // Waiting time

} Process;

// Function to sort the processes based on burst time (Shortest Job First)

void sortProcessesByBurstTime(Process processes[], int n) {

Process temp;

for (int i = 0; i < n-1; i++) {

for (int j = i+1; j < n; j++) {

if (processes[i].burstTime > processes[j].burstTime) {

// Swap the processes

temp = processes[i];

processes[i] = processes[j];

processes[j] = temp;

}
// Function to calculate SJF scheduling

void sjfScheduling(Process processes[], int n) {

int currentTime = 0;

// Sort the processes by burst time

sortProcessesByBurstTime(processes, n);

// Calculate completion time, turnaround time, and waiting time

for (int i = 0; i < n; i++) {

// Update completion time

processes[i].completionTime = currentTime + processes[i].burstTime;

// Calculate turnaround time and waiting time

processes[i].turnAroundTime = processes[i].completionTime -
processes[i].arrivalTime;

processes[i].waitingTime = processes[i].turnAroundTime - processes[i].burstTime;

// Update current time

currentTime = processes[i].completionTime;

// Function to print the process details

void printProcessDetails(Process processes[], int n) {

printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\


tWaiting Time\n");

for (int i = 0; i < n; i++) {

printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",

processes[i].processID,

processes[i].arrivalTime,

processes[i].burstTime,

processes[i].completionTime,

processes[i].turnAroundTime,

processes[i].waitingTime);

float totalTAT = 0, totalWT = 0;

for (int i = 0; i < n; i++) {

totalTAT += processes[i].turnAroundTime;

totalWT += processes[i].waitingTime;

printf("\nAverage Turnaround Time: %.2f\n", totalTAT / n);

printf("Average Waiting Time: %.2f\n", totalWT / n);

int main() {

int n;
// Get the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

Process processes[n];

// Get the arrival time and burst time for each process

for (int i = 0; i < n; i++) {

processes[i].processID = i + 1;

printf("Enter arrival time and burst time for process %d: ", i + 1);

scanf("%d %d", &processes[i].arrivalTime, &processes[i].burstTime);

// Perform SJF scheduling

sjfScheduling(processes, n);

// Print the process details and statistics

printProcessDetails(processes, n);

return 0;

}
QUESTION 9: Write a program to implement non-preemptive priority-based scheduling
algorithm

#include <stdio.h>

typedef struct {

int processID; // Process ID

int arrivalTime; // Arrival time

int burstTime; // Burst time

int priority; // Priority

int completionTime; // Completion time

int turnAroundTime; // Turnaround time

int waitingTime; // Waiting time

} Process;

// Function to sort processes based on priority (ascending order)


void sortProcessesByPriority(Process processes[], int n) {

Process temp;

for (int i = 0; i < n - 1; i++) {

for (int j = i + 1; j < n; j++) {

// Swap if the priority of the current process is greater than the next process

if (processes[i].priority > processes[j].priority) {

temp = processes[i];

processes[i] = processes[j];

processes[j] = temp;

// Function to calculate Non-Preemptive Priority Scheduling

void priorityScheduling(Process processes[], int n) {

int currentTime = 0;

// Sort the processes based on priority

sortProcessesByPriority(processes, n);

// Calculate completion time, turnaround time, and waiting time

for (int i = 0; i < n; i++) {


if (currentTime < processes[i].arrivalTime) {

currentTime = processes[i].arrivalTime;

processes[i].completionTime = currentTime + processes[i].burstTime;

processes[i].turnAroundTime = processes[i].completionTime -
processes[i].arrivalTime;

processes[i].waitingTime = processes[i].turnAroundTime - processes[i].burstTime;

currentTime = processes[i].completionTime;

// Function to print the process details

void printProcessDetails(Process processes[], int n) {

printf("\nProcess\tArrival Time\tBurst Time\tPriority\tCompletion Time\tTurnaround


Time\tWaiting Time\n");

for (int i = 0; i < n; i++) {

printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",

processes[i].processID,

processes[i].arrivalTime,

processes[i].burstTime,

processes[i].priority,

processes[i].completionTime,

processes[i].turnAroundTime,
processes[i].waitingTime);

float totalTAT = 0, totalWT = 0;

for (int i = 0; i < n; i++) {

totalTAT += processes[i].turnAroundTime;

totalWT += processes[i].waitingTime;

printf("\nAverage Turnaround Time: %.2f\n", totalTAT / n);

printf("Average Waiting Time: %.2f\n", totalWT / n);

int main() {

int n;

// Get the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

Process processes[n];

// Get the arrival time, burst time, and priority for each process
for (int i = 0; i < n; i++) {

processes[i].processID = i + 1;

printf("Enter arrival time, burst time, and priority for process %d: ", i + 1);

scanf("%d %d %d", &processes[i].arrivalTime, &processes[i].burstTime,


&processes[i].priority);

// Perform priority scheduling

priorityScheduling(processes, n);

// Print the process details and statistics

printProcessDetails(processes, n);

return 0;

QUESTION 10: Write a program to implement SRTF scheduling algorithm

#include <stdio.h>
#include <limits.h>

typedef struct {

int pid; // Process ID

int arrival; // Arrival time

int burst; // Burst time

int remaining; // Remaining time

int completion; // Completion time

int turnaround; // Turnaround time

int waiting; // Waiting time

} Process;

void srtf(Process processes[], int n) {

int time = 0, completed = 0, shortest = -1;

int min_remaining_time = INT_MAX;

int is_process_available = 0;

while (completed != n) {

// Find the process with the shortest remaining time at the current time

for (int i = 0; i < n; i++) {

if (processes[i].arrival <= time && processes[i].remaining > 0 &&

processes[i].remaining < min_remaining_time) {

min_remaining_time = processes[i].remaining;
shortest = i;

is_process_available = 1;

if (!is_process_available) {

// If no process is available, increment time and continue

time++;

continue;

// Process the shortest job

processes[shortest].remaining--;

min_remaining_time = processes[shortest].remaining;

if (processes[shortest].remaining == 0) {

// Process completed

processes[shortest].completion = time + 1;

processes[shortest].turnaround = processes[shortest].completion -
processes[shortest].arrival;

processes[shortest].waiting = processes[shortest].turnaround -
processes[shortest].burst;

completed++;
shortest = -1;

min_remaining_time = INT_MAX;

time++;

is_process_available = 0;

void display_process_table(Process processes[], int n) {

float total_turnaround = 0, total_waiting = 0;

printf("\nProcess\tArrival\tBurst\tCompletion\tTurnaround\tWaiting\n");

for (int i = 0; i < n; i++) {

total_turnaround += processes[i].turnaround;

total_waiting += processes[i].waiting;

printf("%d\t%d\t%d\t%d\t\t%d\t\t%d\n",

processes[i].pid,

processes[i].arrival,

processes[i].burst,

processes[i].completion,

processes[i].turnaround,
processes[i].waiting);

printf("\nAverage Turnaround Time: %.2f\n", total_turnaround / n);

printf("Average Waiting Time: %.2f\n", total_waiting / n);

int main() {

int n;

printf("Enter the number of processes: ");

scanf("%d", &n);

Process processes[n];

printf("Enter arrival time and burst time for each process:\n");

for (int i = 0; i < n; i++) {

processes[i].pid = i + 1;

printf("Process %d:\n", i + 1);

printf("Arrival time: ");

scanf("%d", &processes[i].arrival);

printf("Burst time: ");

scanf("%d", &processes[i].burst);

processes[i].remaining = processes[i].burst; // Initialize remaining time

}
srtf(processes, n);

display_process_table(processes, n);

return 0;

QUESTION 11: Write a program to calculate sum of n numbers using Pthreads. A list
of n numbers is divided into two smaller list of equal size, two separate threads are used to
sumthe sub lists.

#include <stdio.h>

#include <pthread.h>

#include <stdlib.h>
typedef struct {

int *array; // Pointer to the sublist

int start; // Starting index of the sublist

int end; // Ending index of the sublist

long long sum; // To store the sum of the sublist

} ThreadData;

// Function executed by each thread

void* calculate_sum(void* arg) {

ThreadData* data = (ThreadData*) arg;

data->sum = 0;

for (int i = data->start; i < data->end; i++) {

data->sum += data->array[i];

return NULL;

int main() {

int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

if (n <= 0) {

printf("Number of elements must be greater than zero.\n");

return 1;

int *numbers = (int*) malloc(n * sizeof(int));

if (!numbers) {

perror("Error allocating memory");

return 1;

printf("Enter the elements:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &numbers[i]);

// Divide the array into two parts

int mid = n / 2;

// Thread data structures for two threads


ThreadData thread1_data = {numbers, 0, mid, 0};

ThreadData thread2_data = {numbers, mid, n, 0};

pthread_t thread1, thread2;

// Create two threads

pthread_create(&thread1, NULL, calculate_sum, &thread1_data);

pthread_create(&thread2, NULL, calculate_sum, &thread2_data);

// Wait for both threads to complete

pthread_join(thread1, NULL);

pthread_join(thread2, NULL);

// Calculate the total sum

long long total_sum = thread1_data.sum + thread2_data.sum;

printf("Sum of the array elements: %lld\n", total_sum);

// Free allocated memory

free(numbers);

return 0;
}

QUESTION 12 Write a program to implement first fit best , best fit and worst fit
allocation strategies.

#include <stdio.h>

#define MAX 10

// Function to perform First-Fit allocation

void firstFit(int blockSize[], int m, int processSize[], int n) {

int allocation[n];

// Initially no process is allocated

for (int i = 0; i < n; i++) {

allocation[i] = -1;

}
// Iterate over all processes

for (int i = 0; i < n; i++) {

// Find the first block that can accommodate the process

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

// Allocate the process to the block

allocation[i] = j;

blockSize[j] -= processSize[i];

break;

// Print the allocation results

printf("\nFirst Fit Allocation:\n");

for (int i = 0; i < n; i++) {

if (allocation[i] != -1) {

printf("Process %d is allocated to Block %d\n", i + 1, allocation[i] + 1);

} else {

printf("Process %d is not allocated\n", i + 1);

}
}

// Function to perform Best-Fit allocation

void bestFit(int blockSize[], int m, int processSize[], int n) {

int allocation[n];

// Initially no process is allocated

for (int i = 0; i < n; i++) {

allocation[i] = -1;

// Iterate over all processes

for (int i = 0; i < n; i++) {

int bestIdx = -1;

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx]) {

bestIdx = j;

}
}

if (bestIdx != -1) {

allocation[i] = bestIdx;

blockSize[bestIdx] -= processSize[i];

// Print the allocation results

printf("\nBest Fit Allocation:\n");

for (int i = 0; i < n; i++) {

if (allocation[i] != -1) {

printf("Process %d is allocated to Block %d\n", i + 1, allocation[i] + 1);

} else {

printf("Process %d is not allocated\n", i + 1);

// Function to perform Worst-Fit allocation

void worstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];

// Initially no process is allocated

for (int i = 0; i < n; i++) {

allocation[i] = -1;

// Iterate over all processes

for (int i = 0; i < n; i++) {

int worstIdx = -1;

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

if (worstIdx == -1 || blockSize[j] > blockSize[worstIdx]) {

worstIdx = j;

if (worstIdx != -1) {

allocation[i] = worstIdx;

blockSize[worstIdx] -= processSize[i];
}

// Print the allocation results

printf("\nWorst Fit Allocation:\n");

for (int i = 0; i < n; i++) {

if (allocation[i] != -1) {

printf("Process %d is allocated to Block %d\n", i + 1, allocation[i] + 1);

} else {

printf("Process %d is not allocated\n", i + 1);

int main() {

int blockSize[MAX], processSize[MAX];

int m, n;

// Take input for memory blocks and process sizes

printf("Enter the number of memory blocks: ");

scanf("%d", &m);
printf("Enter the number of processes: ");

scanf("%d", &n);

printf("\nEnter the sizes of memory blocks:\n");

for (int i = 0; i < m; i++) {

scanf("%d", &blockSize[i]);

printf("\nEnter the sizes of processes:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &processSize[i]);

// Call the memory allocation strategies

firstFit(blockSize, m, processSize, n);

bestFit(blockSize, m, processSize, n);

worstFit(blockSize, m, processSize, n);

return 0;

You might also like