OS practical Notes
OS practical Notes
2. cd (Change Directory)
6. cp (Copy)
7. mv (Move or Rename)
8. rm (Remove)
File Manipulation :- Means there are different types of operation that we can perform in the file.
Example – we create file , delete file, write some content in file , Some update inside the file.
System calls : - System call is a way for a user program to request services from O.S. since user program or instruction cannot directly interact
with hardware or the kernel.
A file descriptor is just a number assigned by the system when you open a file.
Example:
Example:
close(fd);
Example:
char buffer[100];
read(fd, buffer, 100);
Example:
Example:
unlink("file.txt");
Example:
rename("old.txt", "new.txt");
Purpose: Fetches file details like size, permissions, and last modified time.
Example:
chmod("file.txt", 0777);
Example:
Example:
link("file.txt", "file_link.txt");
Example:
symlink("file.txt", "file_symlink.txt");
int main() {
int fd = open("file.txt", O_CREAT | O_WRONLY, 0644); open() is used to create or . open a file.
"file.txt" → The name of the file.
O_CREAT → Create the file if it doesn’t exist .
write(fd, "Hello, System Call!\n", 21); write(fd, buffer, size) writes data to the file.
fd → File descriptor (the file
to write to).
"Hello, System Call!\n" →
The text to write.
21 → The number of bytes
(characters) to write, including \n.
close(fd); // Close file
return 0;
}
int main() {
int fd; // File descriptor
char buffer[100];
// Buffer to store file content, This is an array (temporary storage) to store the file's content while reading.
int bytes = read(fd, buffer, sizeof(buffer)); // read(fd, buffer, sizeof(buffer)) reads from the file into buffer.
It stores how many bytes were actually read in the variable bytes.
write(1, buffer, bytes); //write(1, buffer, bytes) writes the read data to the screen.
1 is the file descriptor for the screen to hold data content.
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd;
char buffer[100];
Example of Lseek
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("file.txt", O_RDWR | O_CREAT, 0644);
lseek(fd, 0, SEEK_END);
fd → File descriptor of "file.txt".
0 → Moves 0 bytes from the reference point.
SEEK_END → Sets position at the end of the file.
This ensures the next write() appends data at the end.//
close(fd);
return 0;
}
int main()
{
//FILE *file = fopen("fileum.txt");
#include <stdio.h>
int main()
{
rename("1.txt", "1new.txt");
return 0;
}
===============Lseek==================
1 Example on lseek.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd;
char buffer[20];
read(fd, buffer,13);
lseek(fd,6, SEEK_SET); //SEEK_SET is a constant used in the lseek() function to set the file pointer to a specific position from the beginning of the file.
Example -2 on lseek
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd = open("testfile1.txt", O_RDWR | O_CREAT, 0666);
lseek(fd,0, SEEK_END); //SEEK_END → Moves the pointer relative to the end of the file.
write(fd, "Kumar" ,5);
lseek(fd,5,SEEK_END);
close(fd);
return 0;
}
=======Stat========
#include <stdio.h>
#include <sys/stat.h> //#include <sys/stat.h> → Includes file status information functions, such as stat().
int main()
{
struct stat s; //The stat structure stores information about a file, such as:st_size → File size (in bytes).
stat("testfile.txt", &s);
printf("size: %ld bytes\n", s.st_size); //s.st_size contains the file size in bytes
return 0;
}
========chmod============
#include <stdio.h>
#include <sys/stat.h>
int main()
{
chmod("testfile.txt", 0777); // Set full read, write, execute permissions
printf("Permissions changed.\n");
return 0;
}
=====Hard Link (link() system call)=======
#include <unistd.h>
int main() {
link("original.txt", "hardlink.txt");
return 0;
}
#include <unistd.h>
int main() {
symlink("original.txt", "symlink.txt");
return 0;
}
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *e; // that is the pointer which is declare e to store directory entry , in c programming.
printf("%s\n", e->d_name); // e->d_name struct dirent member (field) that store file and folder name.
closedir(d);
}
Change Directory (chdir())
#include <unistd.h>
int main() {
chdir("/home");
#include <sys/stat.h>
int main() {
mkdir("newdir", 0777);
#include <unistd.h>
int main() {
rmdir("newdir");
#include <stdio.h>
#include <unistd.h>
int main() {
char path[100];
getcwd(path, sizeof(path));
printf("%s\n", path);
Question - C Program to Demonstrate the Use of getcwd, chdir, and rmdir System Calls.
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
// Get current directory, change to /home, and print the new directory
if (getcwd(cwd, sizeof(cwd)) && printf("Current dir: %s\n", cwd) && chdir("/home") == 0 && getcwd(cwd, sizeof(cwd))
&& printf("New dir: %s\n", cwd) == 0 && rmdir("empty_directory") == 0) {
printf("Removed empty directory.\n");
} else {
printf("Error occurred.\n");
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
// Get current directory, change to /home, and print the new directory
if (getcwd(cwd, sizeof(cwd)) && printf("Current dir: %s\n", cwd) && chdir("/home") == 0 && getcwd(cwd, sizeof(cwd))
&& printf("New dir: %s\n", cwd) == 0 && rmdir("empty_directory") == 0) {
printf("Removed empty directory.\n");
} else {
printf("Error occurred.\n");
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
// Get current directory, change to /home, and print the new directory
if (getcwd(cwd, sizeof(cwd)) && printf("Current dir: %s\n", cwd) && chdir("/home") == 0 && getcwd(cwd, sizeof(cwd))
&& printf("New dir: %s\n", cwd) == 0 && rmdir("empty_directory") == 0) {
printf("Removed empty directory.\n");
} else {
printf("Error occurred.\n");
}
return 0;
}
Process Management is an important function of the operating system that helps in creating,exeuting, controlling and ,
executing, controlling and terminating processes.
Process Management is a key function of the OS that controls process creation, execution, and termination.
#include <stdio.h>
#include <unistd.h>
int main() {
fork(); // Create a child process
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Executing 'ls -l' command..\n");
execl("/bin/ls", "ls", "-l", NULL);
printf("exec() failed!\n"); // This will execute only if exec fails
return 1;
}
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Current Process ID: %d\n", getpid());
printf("Parent Process ID: %d\n", getppid());
return 0;
}
sleep() – Delaying Execution
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Sleeping for 3 seconds...\n");
sleep(3);
printf("Process woke up!\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Process is terminating...\n");
exit(0); // Successful termination, 0 indicates successful termination.
}
wait() makes the parent wait until the child process finishes execution.
Without wait(), the parent may finish first, leaving the child as an orphan process.
If pid > 0, we are in the parent process.
If pid == 0, we are in the child process.
If pid < 0, an error occurred (not handled in this code).
#include <stdio.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int pid = fork();
if(pid>0) //If pid > 0, this is the parent process.
{
wait(NULL); //makes the parent wait for the child to complete before proceeding.
printf("child process completed\n");
}
else
{
printf("child process running\n");
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main() {
int priority = nice(5); // Increases priority value
printf("New priority: %d\n", priority);
return 0;
}
Kill()
Used to terminate another process.
Sends a signal to the target process to stop it.
Can forcefully terminate a process using kill(pid, SIGKILL);.
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int pid = fork();
A Thread is smallest unit of execution in a Process. Process can have multiple threads ,Threads can help the program
run faster by doing multiple things at once.
Multiple threads = Multiple tasks at the same time to improve performance by utilizing cpu efficiently. make programs
faster and more responsive.
pthread stands for POSIX (Portable Operating System Interface) Threads, which is a library used in C and C++
programming to allow a program to run multiple threads at the same time.
-pthread: This is flag , It tells the compiler to include pthread support when compiling the program.
When we run a C program, the operating system automatically creates the main thread. This thread runs
inside the main() function. So, in a C program, the main thread is the thread that executes the main()
function.
We can use the pthread_self() function to check which thread is the main thread.
#include <stdio.h>
#include <pthread.h>
int main() {
printf("Main Thread ID: %lu\n", pthread_self());
return 0;
}
Commonly used library functions related to POSIX threads (pthread) :-
1. pthread_create () - Create a new thread
#include <pthread.h>
#include <stdio.h>
return 0; }
2- pthread_join - Wait for termination of a specific thread
Syntax - int pthread_join(pthread_t thread, void **retval);
3 - pthread_exit()
#include <pthread.h>
#include <stdio.h>
int main() {
pthread_t thread_id;
4 - pthread_cancel()
It asks the target thread to stop. However, it doesn’t immediately stop the thread, it will stop when
it,reaches a cancellation point (a safe point where it can stop).
#include <pthread.h>
#include <stdio.h>
#include <unistd.h> // For sleep()
int main() {
pthread_t thread_id;
[&thread_id-This is a pointer to a pthread_t variable that will store the thread ID of the newly
created thread.
NULL, it means the thread will use the default attributes.
thread_function -This is a pointer to the function that the new thread will execute.
Null – argument passed to the thread_funtion)]
#include <stdio.h>
#include <pthread.h>
int main() {
pthread_t thread;
int* result;
return 0;
}
Create a pthread program to find the length of strings passed to the thread function.
#include <stdio.h>
#include <pthread.h>
#include <string.h>
int main() {
pthread_t thread;
char str[] = "Hello, pthread!";
int* length;
Synchronization
Race Condition
Occurs when multiple threads/processes access shared resources without proper synchronization.
Leads to unpredictable or incorrect results due to timing issues.
Semaphore
Definition: synchronization establish between processes or threads, semaphore is abstract data type.
Types:
Functions:
Definition: Ensures exclusive access to a shared resource – synchronization establish between threads.
Types:
Functions:
Usage: Ensures mutual exclusion, protects shared data, prevents simultaneous access.
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int x = 0;
sem_t sem; // Declare a semaphore
void* task() {
sem_wait(&sem); // Acquire lock (enter critical section)
x = x + 1;
pthread_t a, b;
pthread_create(&a, NULL, task, NULL);
pthread_create(&b, NULL, task, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
if (x != 2) {
printf("Race condition detected! x = %d\n", x); ;
} else {
printf(" x = %d\n", x);
}
}
sem_destroy(&sem); // Cleanup
return 0;
#include<stdio.h>
#include<pthread.h>
int x=0;
void* task()
{
x=x+1;
}
int main()
{
int i;
for (i = 0; i < 1000; i++) {
x = 0; // Reset before each run
pthread_t a,b;
pthread_create(&a,NULL,task,NULL);
pthread_create(&b,NULL,task,NULL);
pthread_join(a,NULL);
pthread_join(b,NULL);
if (x != 2) {
printf("Race condition found x = %d\n", x);
} else {
printf(" x = %d\n", x);
} }
return 0;
}