0% found this document useful (0 votes)
4 views24 pages

OS 1 AND 2

The document outlines the implementation of three CPU scheduling algorithms in C: FCFS (First Come First Serve), SJF (Shortest Job First), and RR (Round Robin). It provides detailed descriptions, algorithms, and sample code for each scheduling method, along with explanations of key concepts such as turnaround time, waiting time, and various CPU scheduling criteria. Additionally, it includes viva questions related to CPU scheduling and the characteristics of each algorithm.

Uploaded by

zkhancsd236762
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)
4 views24 pages

OS 1 AND 2

The document outlines the implementation of three CPU scheduling algorithms in C: FCFS (First Come First Serve), SJF (Shortest Job First), and RR (Round Robin). It provides detailed descriptions, algorithms, and sample code for each scheduling method, along with explanations of key concepts such as turnaround time, waiting time, and various CPU scheduling criteria. Additionally, it includes viva questions related to CPU scheduling and the characteristics of each algorithm.

Uploaded by

zkhancsd236762
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/ 24

Program 1.

1: Write a C Program to simulate the FCFS


(First Come First Server) CPU scheduling algorithm.

Aim: To implement FCFS CPU scheduling algorithm in c

Description:
First in, first out (FIFO), also known as first come, first served (FCFS), is the simplest
scheduling algorithm. FIFO simply queues processes in the order that they arrive in the ready
queue. In this, the process that comes first will be executed first and next process starts only
after the previous gets fully executed. We are given with the n number of processes i.e. P1,
P2, P3,.......,Pn and their corresponding burst times. The task is to find the average waiting
time and average turnaround time using FCFS CPU Scheduling algorithm. Here we are
considering that arrival time for all processes is 0.

 Turnaround Time is the time interval between the submission of a process and its
completion.
Turnaround Time = completion of a process – submission of a process
 Waiting Time is the difference between turnaround time and burst time
Waiting Time = turnaround time – burst time

Algorithm:
1. Start
2. Declare the following array to maximum size 15.
a. WT[ MAX ] to store waiting time of each process.
b. BT[ MAX ] to store Burst time of each process.
c. TT [ MAX ] to store turnaround time of each process.
3. Read the number of processes.
4. Read the Burst time for all the processes.
5. Calculate the waiting time of each process
a. WT [ i ] = WT [ i-1] + BT [i-1]
6. Calculate the Turnaround time of each process
a. TT [ i ] = WT [ i ] + BT [ i ]
7. Calculate average waiting time and average turnaround time.
8. Display all the values
9. Stop.

Program:

#include<stdio.h>
int main()
{
int processes[] = { 1, 2, 3};
int n =3;
int bt[] = {10, 5, 8};

int wt[n], tat[n], total_wt = 0, total_tat = 0;

wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;

// calculating turnaround time


for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];

//Display processes along with all details


printf("Processes Burst time Waiting time Turn around time\n");

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf(" %d ",(i+1));
printf(" %d ", bt[i] );
printf(" %d",wt[i] );
printf(" %d\n",tat[i] );
}
int s=(float)total_wt / (float)n;
int t=(float)total_tat / (float)n;
printf("Average waiting time = %d",s);
printf("\n");
printf("Average turn around time = %d ",t);

return 0;
}

OUTPUT
RUN 1:

Processes Burst time Waiting time Turn around time


1 10 0

10

2 5 10

15

3 8 15

23

Average waiting time = 8

Average turn around time = 16

VIVA Questions:
1. What are the features of FCFS scheduling algorithm?

a. Jobs are executed on first come, first serve basis.


b. It is a non-preemptive scheduling algorithm.
c. Easy to understand and implement.
d. Its implementation is based on FIFO queue.
e. Poor in performance as average wait time is high.

2. What is CPU scheduling ()?


Whenever the CPU becomes idle, it is the job of the CPU Scheduler to select another
process from the ready queue to run next by CPU.
or
CPU scheduling is technique through which a process from the ready queue is selected
for execution by CPU.
3. Name some of the CPU Scheduling Algorithm.
a. FCFS (First-Come First-Serve Scheduling)
b. SJF(Shortest-Job-First Scheduling)
c. Priority scheduling.
d. Round Robin scheduling.
e. Multilevel Queue scheduling.
f. Multilevel feedback queue scheduling.
4. What is preemptive scheduling?
In preemptive scheduling the resources are allocated to a process for a limited time, and
process can be interrupted in between.
5. What is non- preemptive scheduling?
In non-preemptive scheduling once resources are allocated to a process, the process holds
it till it completes its burst time or switches to waiting state. Process cannot be interrupted
till it terminates or switches to waiting state.
6. What are CPU scheduling criteria ?
There are several different criteria to consider when trying to select the "best" scheduling
algorithm for a particular situation and environment, including:
i. CPU utilization
ii. Throughput
iii. Turnaround time
iv. Waiting time
v. Response time

7. What is the Process in OS?

Applications run on the computer. The running or execution instance of an application is


called as the process. It is also considered as an execution unit.

8. What is the Thread in OS?

The process may contain multiple threads. Suppose you have notepad application installed on
your system. You click on notepad icon to note down some points. The process starts
running. Then you open another instance of notepad to save other data. The two threads are
created to run two instances of the notepad. You can work on any of the opened notepad
windows independently.

9. Difference Between Process and Thread

 The thread is also called as a lightweight process. It requires fewer resources as


compare to process to run.
 One single process can consist of multiple threads.
 Every process requires its own address space to run on a processor. Whereas threads
within a single process share the single address space. So threads are easier to create
than process.
 Threads read and write at the same place. It is good and easy for the communication
between multiple threads in the single process.
 The data communications between multiple processes are difficult and it is carried out
by IPC (inter-process communication).
 Context switching overhead is less in the thread as compare to process. So threads
decrease overall execution time and the cost of the communication.
 Threads are useful to execute lightweight task whereas processes are responsible for
running heavyweight tasks.
Program 1.2 : Write a C Program to simulate the SJF (
Shortest Job First) CPU scheduling algorithm.

Aim: To implement SJF CPU scheduling algorithm in c

Description: Shortest Job First (SJF) is an algorithm in which the process having the smallest
execution time is chosen for the next execution. This scheduling method can be preemptive or non-
preemptive. It significantly reduces the average waiting time for other processes awaiting execution.
The full form of SJF is Shortest Job First.

Algorithm:
10. Start
11. Declare Process structure with following members.
a. PID : to Store Process ID
b. WT : to store waiting time of process.
c. BT : to store Burst time of process.
d. TT : to store turnaround time of process.
12. Read the number of processes.
13. Read the Burst time and Process Id for all the processes.
14. Sort the Array of process structure based on Burt time.
15. Calculate the waiting time of each process
a. After sorting first process in the list will have waiting time 0
i. Proc[0] .wt = 0
b. Find Waiting time for all other process
i. Proc[ i ] . wt = Proc[ i-1] .wt + Pro [ i-1] .bt
16. Calculate the Turnaround time of each process
i. Proc[ i ] . tt = Proc[ i] .wt + Pro [ i] .bt
17. Calculate average waiting time
a. Total_waitingTime / Number of Process
18. Calculate average turnaround time.
a. Total_waitingTime / Number of Process
19. Display all the values
20. Stop.

Program:
#include <stdio.h>
#define MAX 15
struct process
{
int pid;
int bt;
int wt;
int tt;
};

int main()
{
struct process proc[MAX], temp;
int n , i , j;
int total_wt=0 , total_tt=0;
float avg_wt, avg_tt;

printf("enter number of process (max of 15) \n");


scanf("%d",&n);

printf(" Enter Process Id and Brust time of the process \n");


for( i=0; i< n; i++)
{
scanf("%d%d", &proc[i].pid , &proc[i].bt );
}
//Bubble sort, to sort the process
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (proc[j].bt > proc[j+1].bt)
{
temp=proc[j];
proc[j]= proc[j+1];
proc[j+1]=temp;
}

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


{
if(i= =0)
{
proc[0].wt=0;
proc[0].tt = proc[0].bt;
}
else
{
proc[i].wt = proc[i-1].wt + proc[i-1].bt; // waiting time calculation
total_wt = total_wt+proc[i].wt; // total waiting time calculation

proc[i].tt = proc[i].wt+proc[i].bt ; // turn around time calculation


total_tt = total_tt+proc[i].tt; // total turn around time calculation
}
}

avg_wt = (float) total_wt/n;


avg_tt = (float) total_tt/n;

printf(" Process ID Burst time Waiting Time Turn Around Time \n");

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


printf(" %d %d %d %d \n", proc[i].pid , proc[i].bt,
proc[i].wt, proc[i].tt);
printf("Average waiting time = %f",avg_wt);
printf("\n");
printf("Average turn around time = %f ",avg_tt);

return 0;

OUTPUT
RUN1 :
enter number of process (max of 15) 4

Enter Process Id and Brust time of the process

2 45

3 56

1 78

47

Process ID Burst time Waiting Time Turn Around Time

4 7 0 7
2 45 7 52
3 56 52 108
1 78 108 186

Viva Questions:

1. What dose scheduling mean?


1. CPU scheduling deals with the problem of deciding which of the processes in the ready
queue is to be allocated the CPU. There are many different CPU scheduling algorithms
2. Scheduling is done to balance the load on the system and ensure equal distribution
of resources and give some prioritization according to set rules. This ensures that a
computer system is able to serve all requests and achieve a certain quality of
service.
3. Scheduling is also known as process scheduling.

2. What are the main concern of scheduler?


1. Throughput, or how fast it can finish a certain number of tasks from beginning to
end per unit of time
2. Latency, which is the turnaround time or the time it takes to finish the task from
the time of request or submission until finish, which includes the waiting time
before it could be served
3. Response time, which is the time it takes for the process or request to be served, in
short the waiting time.

3. What does Shortest Job First (SJF) mean?


1. Shortest job first is a scheduling algorithm in which the process with the smallest
execution time is selected for execution next. Shortest job first can be either
preemptive or non-preemptive.
2. It also reduces the average waiting time for other processes awaiting execution.

3. Shortest job first is also known as shortest job next (SJN) and shortest process
next (SPN).

4. What are different CPU scheduling criteria?


1. CPU utilization – keep the CPU as busy as possible
2. Throughput – Number of processes that complete their execution per time unit
3. Turnaround time – amount of time to execute a particular process
4. Waiting time – amount of time a process has been waiting in the ready queue
5. Response time – amount of time it takes from when a request was submitted until
the first response is produced, not output (for time-sharing environment)

5. What are the disadvantages of SJF


1. It can cause process starvation for longer jobs if there are a large number of
shorter processes.
2. The need to know the execution time for each process beforehand. Often, this is
almost impossible in many environments.

6. What are Scheduling Algorithm Optimization Criteria


1. Max CPU utilization
2. Max throughput
3. Min turnaround time
4. Min waiting time
5. Min response time

7. What is starvation ?
Starvation or indefinite blocking is phenomenon associated with the Priority
scheduling algorithms, in which a process ready to run for CPU can wait indefinitely
because of low priority. In heavily loaded computer system, a steady stream of
higher-priority processes can prevent a low-priority process from ever getting the
CPU.
Program 1.3: Write a C Program to simulate the RR (
Round Robin ) CPU scheduling algorithm.

AIM: To implement RR CPU scheduling algorithm in c

Description: The round-robin (RR) scheduling is designed especially for time-sharing


systems. It is similar to FCFS scheduling, but preemption is added to switch between process.
A small unit of time, called a time quantum, or time slice, is defined. A time quantum is
generally from 10 to 100ms. The ready queue is treated as a circular queue. RR goes around
the ready queue, allocating the CPU to each process for a time interval of up to 1 time
quantum. RR is preemptive. The performance of RR depends heavily on the size of the time
quantum selected. At one extreme, if the quantum is very large (infinite), RR is the same as
the FCFS policy. If the time quantum is very small, it would appear each process among n
processes has its own processor running at 1/n the speed of the real processor.

ALGORITHM:

21. Start
22. Declare Process structure with following members.
a. PID : to Store Process ID
b. WT : to store waiting time of process.
c. BT : to store Burst time of process.
d. TT : to store turnaround time of process.
e. rem_bt : to store remaining burst time
23. Read the number of processes.
24. Read the Burst time and Process Id for all the processes.
25. Read the time quantum value.
26. The process are selected from the queue in first come first serve order and
following steps are repeated until remaining burst time for all process is zero.
a. If Burst time > time quantum
i. The process is preempted after time quantum and added to the end
of the queue. Remaing burst time is recorded. CPU execution time
is also recorded
1. t = t + quantum
2. Proc[i] . rem_bt = Proc[i].rem_bt - quantum
b. If Burst Time <= time quantum
i. Process remaining burst time is set to zero and waiting time is
calculated
1. t = t + Proc[i] . rem_bt
2. Proc[i] . rem_bt = 0
3. Proc[ i ] .wt = t - Proc [ i ] .bt
27. Calculate the Turnaround time of each process
i. Proc[ i ] . tt = Proc[ i] .wt + Pro [ i] .bt
28. Calculate average waiting time
a. Total_waitingTime / Number of Process
29. Calculate average turnaround time.
a. Total_waitingTime / Number of Process
30. Display all the values
31. Stop.

Program:

#include <stdio.h>
#define MAX 15
struct process
{
int pid;
int bt;
int wt;
int tt;
int rem_bt;
};

int main()
{
struct process proc[MAX] ;
int n , i , j ,quantum , t;
int total_wt=0 , total_tt=0;
float avg_wt, avg_tt;
int done=0;

printf("enter number of process (max of 15) \n");


scanf("%d",&n);

printf(" Enter Process Id and Brust time of the process \n");


for( i=0; i< n; i++)
{
scanf("%d%d", &proc[i].pid , &proc[i].bt );
proc[i].rem_bt = proc[i].bt;
}

printf("Enter time Quantum \n");


scanf("%d",&quantum);

t = 0;
// Keep traversing processes in round robin manner until all of them are not done.
printf("Order of Process Excecution is \n");

do
{
done = 1;
for (int i = 0 ; i < n; i++) // Traverse all processes one by one repeatedly
{
// If burst time of a process is greater than 0 then only need to process further
if (proc[i].rem_bt > 0)
{
done = 0; // There is a pending process
printf(" %d : ",proc[i].pid);
if (proc[i].rem_bt > quantum)
{
// Increase the value of t which shows how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process by quantum


proc[i].rem_bt= proc[i].rem_bt - quantum;
}
// If burst time is smaller than or equal to quantum. Last cycle for this process
else
{
// Increase the value of t, which shows how much time a process has been processed
t = t + proc[i].rem_bt;

// Waiting time is current time minus time used by this process


proc[i].wt = t - proc[i].bt;

// As the process gets fully executed make its remaining burst time = 0
proc[i].rem_bt = 0;
}
}
}
}while(done != 1);
printf("\n");
for (i = 0; i < n; i++)
{
total_wt = total_wt + proc[i].wt; // total waiting time calculation
proc[i].tt = proc[i].wt + proc[i].bt ; // turn around time calculation
total_tt = total_tt + proc[i].tt; // total turn around time calculation

}
avg_wt = (float) total_wt/n;
avg_tt = (float) total_tt/n;

printf(" | PID | BT | WT | TaT | \n");

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


printf(" %d : %d : %d : %d \n", proc[i].pid , proc[i].bt , proc[i].wt ,
proc[i].tt );
printf("Average waiting time %f \n, ", avg_wt);
printf("Average Turn around time %f \n " ,avg_tt);
return 0;

}
enter number of process (max of 15)
4
Enter Process Id and Brust time of the process
1 4
2 3
3 5
4 6
Enter time Quantum
2
Order of Process Excecution is
1: 2: 3: 4: 1: 2: 3: 4: 3: 4:
Processes are executed in following order
PID | BT | WT | TaT
1 : 4 : 6 : 10
2 : 3 : 8 : 11
3 : 5 : 11 : 16
4 : 6 : 12 : 18
Average waiting time 9.250000
Average Turnaround time 13.750000

VIVA QUESTIONS
1. What are the characteristic of RR?
a. Round Robin is a CPU scheduling algorithm where each process is assigned a fixed
time slot in a cyclic way.
b. It is simple, easy to implement, and starvation-free as all processes get fair share of
CPU.
c. One of the most commonly used technique in CPU scheduling as a core.
d. It is preemptive as processes are assigned CPU only for a fixed slice of time at most.
e. The disadvantage of it is more overhead of context switching.

2. What are the advantage of RR?


A big advantage of round robin scheduling over non-preemptive schedulers is that it
dramatically improves average response times. By limiting each task to a certain amount of
time, the operating system can ensure that it can cycle through all ready tasks, giving each
one a chance to run.
3. What are disadvantages of RR ?
Giving every process an equal share of the CPU is not always a good idea. For instance,
highly interactive processes will get scheduled no more frequently than CPU-bound
processes.

4. What does Round Robin Scheduling (RRS) mean?Round robin scheduling (RRS) is a
job-scheduling algorithm that is considered to be very fair, as it uses time slices that are
assigned to each process in the queue or line. Each process is then allowed to use the CPU
for a given amount of time, and if it does not finish within the allotted time, it is
preempted and then moved at the back of the line so that the next process in line is able to
use the CPU for the same amount of time.

Program 1.4 : Write a C Program to simulate the Priority


CPU scheduling algorithm.

Aim: To implement Priority CPU scheduling algorithm in c

Description: In priority scheduling, a priority is associated with each process, and the CPU
is allocated to the process with the highest priority. Equal-priority processes are scheduled in
FCFS order. SJF is simply a priority algorithm where the priority (p) is the inverse of the
(predicted) next CPU burst. The large the CPU burst, the lower the priority. Priorities are
generally some fixed range of numbers, such as 0 to 7. In this text, we assume that low
numbers represent high priority.

Algorithm:
a. Start
b. Declare Process structure with following members.
i. PID : to Store Process ID
ii. Priority : to store priority of the process
iii. WT : to store waiting time of the process.
iv. BT : to store Burst time of the process.
v. TT : to store turnaround time of the process.
c. Read the number of processes.
d. Read the Process Id, Burst time and Priority for all the processes.
e. Sort the Array of process structure based on Priority.
f. Calculate the waiting time of each process
a. After sorting first process in the list will have waiting time 0
i. Proc[0] .wt = 0
b. Find Waiting time for all other process
i. Proc[ i ] . wt = Proc[ i-1] .wt + Pro [ i-1] .bt
32. Calculate the Turnaround time of each process
i. Proc[ i ] . tt = Proc[ i] .wt + Pro [ i] .bt
33. Calculate average waiting time
a. Total_waitingTime / Number of Process
34. Calculate average turnaround time.
a. Total_waitingTime / Number of Process
35. Display all the values
36. Stop.

#include <stdio.h>
#define MAX 15
struct process
{
int pid;
int priority;
int bt;
int wt;
int tt;
};

int main()
{
struct process proc[MAX], temp;
int n , i , j;
int total_wt=0 , total_tt=0;
float avg_wt, avg_tt;
printf("enter number of process (max of 15) \n");
scanf("%d",&n);

printf(" Enter Process Id and Brust time and priority of the process \n");
for( i=0; i< n; i++)
{
scanf("%d%d%d", &proc[i].pid , &proc[i].bt , &proc[i].priority);
}
//Bubble sort, to sort the process
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (proc[j].priority > proc[j+1].priority)
{
temp=proc[j];
proc[j]= proc[j+1];
proc[j+1]=temp;
}

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


{
if(i==0)
{
proc[0].wt=0;
proc[0].tt = proc[0].bt;
}
else
{
proc[i].wt = proc[i-1].wt + proc[i-1].tt; // waiting time calculation
total_wt = total_wt + proc[i].wt; // total waiting time calculation

proc[i].tt = proc[i].wt + proc[i].bt ; // turn around time calculation


total_tt = total_tt + proc[i].tt; // total turn around time calculation
}
}

avg_wt = (float) total_wt/n;


avg_tt = (float) total_tt/n;

printf(" | Process ID | Priority | Burst time | Waiting Time | Turn Around Time | \n");

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


printf(" | %d | %d | %d | %d | %d | \n", proc[i].pid ,
proc[i].priority, proc[i].bt, proc[i].wt, proc[i].tt);
return 0;

OUTPUT:

enter number of process (max of 15)


4
Enter Process Id and Brust time and priority of the process
3 55 6
4 5 9
3 10 2
7 20 1

| Process ID | Priority | Burst time | Waiting Time | Turn Around Time |


| 7 | 1 | 20 | 0 | 20 |
| 3 | 2 | 10 | 20 | 30 |
| 3 | 6 | 55 | 50 | 105 |
| 4 | 9 | 5 | 155 | 160 |

VIVA Questions

1. What is Priority Scheduling?


Priority scheduling is a method of scheduling processes based on priority. In this
method, the scheduler chooses the tasks to work as per the priority. Priority
scheduling involves priority assignment to every process, and processes with higher
priorities are carried out first, whereas tasks with equal priorities are carried out on a
first-come-first-served (FCFS).

2. Is Priority Scheduling Preemptive or non-preemtive?


Priority scheduling can be either of the following:
Preemptive: This type of scheduling may preempt the central processing unit
(CPU) in the case the priority of the freshly arrived process being greater than those
of the existing processes.
Non-preemptive: This type of scheduling algorithm simply places the new
process at the top of the ready queue.
3. Disadvantage of Priority Scheduling ?
Indefinite blocking, otherwise called starvation, is one of the major issues
concerning priority scheduling algorithms. It is a state where a process is ready to be
executed, but faces a long wait in getting assigned to the CPU.It is often possible that
a priority scheduling algorithm can make a low-priority process wait indefinitely. For
example, in an intensely loaded system, if there are a number of higher priority
processes, the low-priority processes may never get the CPU for execution.

4. What is aging?
A remedy to starvation is aging, which is a technique used to gradually
increase the priority of those processes that wait for long periods in the system.

2. Programs to implement following system calls of UNIX


operating system: fork, exec, getpid, exit, wait, close, stat,
opendir, readdir ,closedir and lseek.

Description:
System Calls:

The way that programs talk to the operating system is via ``system calls.''

A system call looks like a procedure call , but it's different -- it is a request to the operating
system to perform some activity.

 System calls are expensive. While a procedure call can usually be performed in a few
machine instructions, a system call requires the computer to save its state, let the
operating system take control of the CPU, have the operating system perform some
function, have the operating system save its state, and then have the operating system
give control of the CPU back to you.
 System calls are system dependent. Knowing this, it would not be a good idea to
directly use system calls when portability cannot be neglected. System calls are also
quite complex. Most often, it involves the duo of TRAP and RET (or some variations
of those two). To implement system call, one would need specialized knowledge of
I/O registers, the sequence of operations needed to use them; and most important of
all, implement enough protection because I/O resources are generally shared among
multiple users and/or processes.

System Calls for I/O


There are 5 basic system calls that Unix provides for file I/O.

1. int open(char *path, int flags [ , int mode ] );


2. int close(int fd);
3. int read(int fd, char *buf, int size);
4. int write(int fd, char *buf, int size);
5. off_t lseek(int fd, off_t offset, int whence);

Program 2.1 Write a C program to read from file and


write to another file.

AIM: To write a C program to copy content from one file to another file.

Program:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>

#define BUFF_SIZE 1000

int main(void)
{

int n,fd1,fd2;
char buff[BUFF_SIZE];

//open the file for reading


fd1 = open("testfile.txt",O_RDWR,0644);

//read the data from file


n=read(fd1,buff,BUFF_SIZE);

// creating a new file using open.


fd2=open("fileforcopy.txt", O_CREAT | O_RDWR, 0777);

//writting data to file (fd)


if( write(fd2, buff, n) == n)
printf("file copying is successful. and the data is:\n");

//Write to display (1 is standard fd for output device)


write(1, buff, n);

//closing the files


int close(int fd1);
int close(int fd2);

return 0;

}
INPUT &OUTPUT:

testfile.txt file copied to fileforcopy.txt


file copying is successful. and the data is: hello mgit

Program 2.2. Program using lseek() system call that reads


10 characters from file “seeking” and print on screen. Skip
next 5 characters and again read 10 characters and write on
screen.

AIM: To write a C program to demonstrate the usage of lseek() system call.


Description:

lseek (C System Call): lseek is a system call that is used to change the location of the
read/write pointer of a file descriptor. The location can be set either in absolute or relative
terms.

off_t lseek(int fildes, off_t offset, int whence);

The lseek() function shall set the file offset for the open file description associated with the
file descriptor fildes, as follows:

 If whence is SEEK_SET, the file offset shall be set to offset bytes.


 If whence is SEEK_CUR, the file offset shall be set to its current location plus offset.
 If whence is SEEK_END, the file offset shall be set to the size of the file plus offset.

The symbolic constants SEEK_SET, SEEK_CUR, and SEEK_END are defined in


<unistd.h>.
Upon successful completion, the resulting offset, as measured in bytes from the beginning of
the file, shall be returned. Otherwise, (off_t)-1 shall be returned, errno shall be set to indicate
the error, and the file offset shall remain unchanged.
Program:
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h
#include<sys/stat.h>
#int main()
{
int n,f;
char buff[10];
f=open("seeking",O_RDWR);
read(f,buff,10);
write(1,buff,10);
read(f,buff,10);
write(1,buff,10);
}
Pre-requisite: Create a file “seeking” and write “1234567890abcdefghijxxxxxxxxxx” into
it.
Output:

The output will be the first 10 characters “1234567890” followed by “fghijxxxxx”. The
inbetween 5 characters are skipped because we used lseek to reposition the pointer 5
characters ahead from the current (SEEK_CUR) position.

Program 2.3: Write a C program to print file status


information using stat function.

AIM: To write a C program to demonstrate the usage of stat() system call.

Description:
Stat system call is a system call in Linux to check the status of a file such as to check
when the file was accessed. The stat() system call actually returns file attributes. The file
attributes of an inode are basically returned by Stat() function. An inode contains the
metadata of the file. An inode contains: the type of the file, the size of the file, when the file
was accessed (modified, deleted) that is time stamps, and the path of the file, the user ID and
the group ID, links of the file, and physical address of file content.

To use the stat system call in C programming language we should include the following
header file:

#include <sys/stat.h>
int stat(const char *path, struct stat *buf)

 The return type of the function in int, if the function is executed successfully, 0 is
returned if there are any errors, -1 will be returned.
 const char *path specifies the name of the file.
 stat structure The data or information about the file is stored which uses a pointer named
buf, which is passed in as a paramteter and filled in during the execution of the call and
readable by the user after the call.

Program :
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include<unistd.h>
struct stat statbuf;
char dirpath[256];

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


{
// getcwd is to get the name of the current working directory if found
getcwd(dirpath,256);
DIR *dir = opendir(dirpath);
struct dirent *dp;

for (dp=readdir(dir); dp != NULL ; dp=readdir(dir))

{
stat(dp->d_name, &statbuf);
printf("the file name is %s \n", dp->d_name);
printf("dir = %d\n", S_ISDIR(statbuf.st_mode));
printf("file size is %ld in bytes \n", statbuf.st_size);
printf("last modified time is %ld in seconds \n", statbuf.st_mtime);
printf("last access time is %ld in seconds \n", statbuf.st_atime);
printf("The device containing the file is %ld\n", statbuf.st_dev);
printf("File serial number is %ld\n\n", statbuf.st_ino);
}
}

OUTPUT:

the file name is fileone.txt


dir = 0
file size is 31 in bytes
last modified time is 1581656490 in seconds
last access time is 1581656969 in seconds
The device containing the file is 2053
File serial number is 2099241

the file name is filestatus.c


dir = 0
file size is 772 in bytes
last modified time is 1581146159 in seconds
last access time is 1581920990 in seconds
The device containing the file is 2053
File serial number is 2099181

Program 2.4 : C Program for opendir(), readdir() and


closedir system calls

AIM: To write a C program to demonstrate the usage of opendir(),


readdir() and closedir() system call.

Description:
The opendir() function shall open a directory stream corresponding to the directory named by
the dirname argument. Directory entries represent files or subdirectory.
#include <dirent.h>
DIR *opendir(const char *dirname);

 Upon successful completion, opendir() shall return a pointer to an object of type


DIR. Otherwise, a null pointer shall be returned and errno set to indicate the error.

The readdir() function shall return a pointer to a structure representing the directory entry at
the current position in the directory stream specified by the argument dirp, and position the
directory stream at the next entry. It shall return a null pointer upon reaching the end of the
directory stream.
* readdir(DIR *dirp);
* Upon successful completion, readdir() shall return a pointer to an object of type
struct dirent. When an error is encountered, a null pointer shall be returned and errno shall
be set to indicate the error.

The closedir() function shall close the directory stream referred to by the argument dirp.
Upon successful completion, closedir() shall return 0; otherwise, -1 shall be returned and
errno set to indicate the error.

PROGRAM:

#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc, char *argv[])
{
char buff[100];
DIR *dirp;
printf("\n\n ENTER DIRECTORY NAME");
scanf("%s", buff);
if( ( dirp=opendir( buff ) ) == NULL)
{
printf("The given directory does not exist");
exit(1);
}
while(dptr = readdir ( dirp ) )
{
printf("%s\n",dptr->d_name);
} closedir(dirp); }
Program 2.5: C Program for fork() and getpid() system call

AIM: To write a C program to demonstrate the usage of fork() and getpid()


system call.

Description: fork() creates a new process by duplicating the calling process.The new
process is referred to as the child process. The calling process is referred to as the parent
process. The child has its own unique process ID.The child's parent process ID is the same as
the parent's process ID.

#include <unistd.h>
pid_t fork(void);
 On success, the PID of the child process is returned in the parent, and 0 is returned in the
child. On failure, -1 is returned in the parent, no child process is created, and errno is set
to indicate the error.

Getpid() is the function used to get the process ID of the process that calls that function.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
STEP 4: If pid==-1, exit.
STEP 5: Ifpid!=-1 , get the process id using getpid().
STEP 6: Print the process id.
STEP 7:Stop the program

PROGRAM:
#include<stdio.h>
#include<unistd.h>
main()
{
int pid,pid1,pid2;
pid=fork();
if(pid== -1)
{
printf("ERROR IN PROCESS CREATION \n");
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf("\n the parent process ID is %d\n", pid1);
}
else
{
pid2=getpid();
printf("\n the child process ID is %d\n", pid2);
}}
2.6 C program to execute another C program using exec
system call.

AIM: To write a C program to execute another C program using exec


system call

Description:
The exec family of functions replaces the current running process with a new process. It can
be used to run a C program by using another C program. It comes under the header file
unistd.h. There are many members in the exec family which are shown below with
examples.

 execvp : Using this command, the created child process does not have to run the same
program as the parent process does. The exec type system calls allow a process to run
any program files, which include a binary executable or a shell script . Syntax:

int execvp (const char *file, char *const argv[]);

file: points to the file name associated with the file being executed.
argv: is a null terminated array of character pointers.

We will have two .C files , EXEC.c and execDemo.c and we will replace the execDemo.c
with EXEC.c by calling execvp() function in execDemo.c .

//EXEC.c

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

int main()
{
int i;

printf("I am EXEC.c called by execvp() ");


printf("\n");
return 0;
}

Now,create an executable file of EXEC.c using command

gcc EXEC.c -o EXEC


//execDemo.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
//A null terminated array of character
//pointers
char *args[]={"./EXEC",NULL};
execvp(args[0],args);

/*All statements are ignored after execvp() call


as this whole
process(execDemo.c) is replaced by another
process (EXEC.c)
*/
printf("Ending-----");

return 0;
}

create an executable file of execDemo.c using command

gcc execDemo.c -o execDemo

After running the executable file of execDemo.cby using command ./excDemo, we


get the following output:

I AM EXEC.c called by execvp()

When the file execDemo.c is compiled, as soon as the statement execvp(args[0],args)


is executed, this very program is replaced by the program EXEC.c. “Ending—–” is
not printed because because as soon as the execvp() function is called, this program is
replaced by the program EXEC.c.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy