0% found this document useful (0 votes)
47 views53 pages

Os - Practical File

The mv command renames and moves a file between directories, so running ls in the destination directory after moving a file displays the new filename, but ls in other directories does not.
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)
47 views53 pages

Os - Practical File

The mv command renames and moves a file between directories, so running ls in the destination directory after moving a file displays the new filename, but ls in other directories does not.
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/ 53

Operating System with Linux (MCA-167) Practical File

BHARATI VIDYAPEETH’S
INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT
(Affiliated to Guru Gobind Singh Indraprastha University,
Approved by AICTE, New Delhi)

Operating System with


Linux(MCA-167)
Practical File

Submitted To: Submitted By:


Dr. Sunil Pratap Singh Shubham Joshi
(03811604422)

Shubham Joshi
(03811604422)
INDEX

S. No. Problem Description Date of Sign.


Execution
AP1 Run ps and note the PID of your shell. Log out and login
again and run ps again. What do you observe?
AP2 Enter the following commands, and note yourobservations:
(i) who and tty,
(ii) tput clear,
(iii) id,
(iv) ps and echo $$.
AP3 Run the following commands, and then invoke ls.What do
you conclude?
echo > README [Enter]
echo > readme [Enter]

AP4 Create a directory, and change to that directory. Next,create


another directory in the new directory, and then change to that
directory too. Now, run $ cd without any arguments followed
by pwd. What do you
conclude?

AP5 Create a file mca containing the words “Hello MCA Class!”.
Now create a directory bvicam, and then runmv mca
bvicam. What do you observe when you run
both ls and ls bar?

AP6 Run $ who am i and then interpret the output.

AP7 Find out whether the following commands are internal


or external: echo, date, pwd, and ls
AP8 Display the current date in the form dd/mm/yyyy.
Both of the following commands try to open the filemca, but the
AP9 error messages are a little different.
What could be the reason? $ cat mca cat: mca: No such file or
directory $ cat < mca bash: mca: No such
file or directory
Run the following commands, and discuss theiroutput?
AP10
(a) $ uname
(b) $ passwd
(c) $ echo $SHELL
(d) $ man man
(e) $ which echo
(f) $ type echo
(g) $ whereis ls
(h) $ cd
(i) $ cd $HOME
(j) $ cd ~
AP11 Frame ls command to
(i) mark directories and executables separately, and
(ii) also display hidden files.
AP12 Find out the result of following: $ cat mca mca mca

AP13 Run the following and determine which commands willwork?


Explain with reasons.
(a) $ mkdir a/b/
(b) $ mkdir a a/b
(c) $ rmdir a/b/c
(d) $ rmdir a a/b
(e) $ mkdir /bin/mca
AP14 How does the command mv mca1 mca2 behave, where both
mca1 and mca2 are directories, when
(i) mca2 exists,
(ii) (ii) mca2 doesn‟t exist?

AP15
Assuming that you are positioned in the directory
/home/bvicam, what are these commands presumedto do, and
explain whether they will work at all:
(a) $ cd ../..
(b) $ mkdir ../bin
(c) $ rmdir .
. (d) $ ls ..
BP1 Apply Peterson algorithm for solving the critical section
problem with C/Java multi-threaded programming. Assume
appropriate code snippet for
critical section

BP2 Apply Bakery algorithm for synchronization of processes/threads


in a C/Java program. Assume
appropriate code snippet for critical section.

BP3 Write C/Java program to simulate and solve theProducer-


Consumer problem
BP4 Implement Semaphore(s) in a C/Java-multithreaded program to
simulate the working and solution of Reader-Writer problem.
Assume multiple readers and
writers

BP5
Create a zombie process and an orphan process in a
„C‟ program with appropriate system calls.
BP6 Write a „C‟ program which creates a new process andallows both,
child and parent, to report their identification numbers (ids). The
parent process
should wait for the termination of the child process

BP7 Write two „C‟ programs (A.c and B.c) where one program (A.c)
creates a child process and then that child process executes the
code of other program (B.c). The logic of program „B.c‟ is to
generate all the
prime numbers within the specified limit.
BP8 Write an appropriate „C‟ program which implementsthe concept
of dynamic memory allocation (use of malloc(), calloc(),
realloc(), and free() system call)
BP9 Create a text file, named as „courses.txt‟ that containsthe following
four lines: Java Programming Operating
System Discrete Structure Write a „C‟ program that
forks three other processes. After forking, the parent process goes
into wait state and waits for the childrento finish their execution.
Each child process reads a line from the „course.txt‟ file (Child 1
Reads Line 1, Child 2 Reads Line 2, and Child 3 Reads Line 3) and
each prints the respective line. The lines can be
printed in any order.

CP1 Write a „C‟ program (using appropriate system calls ofLinux) that
generates „n‟ integers and stores them in atext file, named as
„All.txt‟. Then, retrieve the stored integers from this file and copy
to “Odd.txt” and
„Even.txt‟ based upon the type of number, i.e. if theretrieved
integer if odd number then store in
„Odd.txt‟ file or if the retrieved integer is even then store in
„Even.txt‟ file. Finally, display the contents of
all three files on the screen

CP2 Write a program in „C‟ which accepts the file or directory name
and permission (access rights) fromthe user and then changes
the access rights
accordingly. Use appropriate system call(s) of Linux.
CP3 Write a „C‟ program (using appropriate system calls ofLinux)
which generates and stores the characters from
„a‟ to „z‟. Then, display the stored characters in
alternative manner, like: a, c, e, g, …, etc.

CP4 Write a „C‟ program (using appropriate system calls ofLinux)


which receives roll number and names of „n‟ students, from the
user one-by-one and then stores them in a text file, named as
„Student.txt‟. After inserting all „n‟ roll numbers and names,
display the contents of file. Also, display the access rights of the
file „Student.txt‟
Demonstrate the use of following system calls bywriting an
appropriate „C‟ program.
(a) lseek()
(b) chmod()
(c) umask()
(d) access()
(e) utime()
AP1: Run ps and note the PID of your shell. Log out and log in again and run ps again. What do
you observe?

ps command is used to list all the processes created by user.


It’s syntax is: $ ps.

After logging out and relogging again, our pid has changed.

AP2 Enter the following commands, and note your observations:


(i)who and tty,
who command is mainly used to find out user’s information.
Syntax: $ who -H

In who command, following are the representations.


NAME -> User ID
LINE -> Device Name
TIME ->Time of Login
COMMENT -> Machine Name

Tty
It represents tele type(terminal name)

(ii) tput clear


It clears the entire screen

(iii) id
It is used to find out user and group names and numeric ID's (UID or group ID) of the current user or any other
user in the server.
(iv) ps
ps command shows the pid and lists all the processes created by user.

echo $$.
Echo is used for displaying lines of text or string which are passed as arguments on the command line.
$$ is the process id of the currently running process .
So it echo $$ will present process id.

AP3 Run the following commands, and then invoke ls. What do you conclude?
echo > README [Enter]
echo > readme [Enter]
echo is used for displaying lines of text or string which are passed as arguments on the command line.
ls is used in listing the contents inside a directory.
AP4 Create a directory, and change to that directory. Next, create another directory in the new
directory, and then change to that directory too. Now, run $ cd without any arguments followed
by pwd. What do you conclude?
mkdir command is used to create directory .
first we created a directory d3 using $ mkdir d3. To switch to that directory, we used $ cd d3. After that, we
created another directory inside d3 using $ mkdir d4. And to switch to that directory, we used $ cd d4.

Now after running cd command followed by pwd command, we came out of the directory.
Pwd command returns us to the current directory and here in this case, as we came out of directories , it didn’t
take us inside any directory.

AP5 Create a file mca containing the words “Hello MCA Class!”. Now create a directory bvicam,
and then run mv mca bvicam. What do you observe when you run both ls and ls bar?
we created a directory using mkdir command
Syntax: $ mkdir bvicam
After that we created another file named mca using cat command.
Syntax: $ cat > mca
mv command is used to rename a directory or file.
Syntax: $ mv oldname newname.
So now, name of file mca is bvicam. As ls command shows the lists of files in current directory, when we use it,
we see file bvicam.
AP6 Run $ who am i and then interpret the output.
It displays the username of the current user when this command is invoked. It allows the user to see currently
logged in users.
Syntax: $ whoami

AP7 Find out whether the following commands are internal or external: echo, date, pwd, and ls.

Built-in commands are internal commands that are built-in the shell. Built-in commands are called from the
shell and executed directly within the shell itself.

External commands are other than built-in commands. These commands are programs which have their own
binary and located in the filesystem. These are the commands that our system offers and are totally shell
independent. Mostly these commands reside in /bin, /sbin, /usr/sbin

Syntax: type <command>


echo is internal command

date is external command

pwd is internal command

ls is internal/shell command

AP8 Display the current date in the form dd/mm/yyyy.


In order to display date in dd/mm/YYYY format, we use certain format specifiers.
Syntax: date +'%d/%m/%Y'
AP9 Both of the following commands try to open the file mca, but the error messages are a little
different. What could be the reason? $ cat mca cat: mca: No such file or directory $ cat < mca
bash: mca: No such file or directory.

when we try to open file mca, it doesn’t get open because earlier we had renamed it to bvicam using mv
command.
And when we use same commands to open bvicam , it opens

AP10 Run the following commands, and discuss their output?


(a) $ uname

(b) $ passwd

(c) $ echo $SHELL

(d) $ man man


(e) $ which echo

(f) $ type echo

(g) $ whereis ls

(h) $ cd

(i) $ cd $HOME
(j) $ cd ~

AP11 Frame ls command to (i) mark directories and executables separately


To mark directories and executables separately, we use ls -F command.
Syntax : $ls -F

and (ii) also display hidden files.


To display hidden files we use -a option.
Syntax: $ls -a

AP12 Find out the result of following: $ cat bvicam bvicam bvicam.
Using this command , the output is displayed thrice in three different lines.
AP13 Run the following and determine which commands will work? Explain with reasons.
(a) $ mkdir a/b/
It will not work due to syntax error.

(b) $ mkdir a a/b


It will create a directory a and a sub directory b inside the directory a.

(c) $ rmdir a/b/c


It will fail because we have’t created any sub directory c.

(d) $ rmdir a a/b


It will not be able to delete directory because we because directory a is not empty.

(e) $ mkdir /bin/mca


it will also show error

AP14 How does the command mv mca1 mca2 behave where both mca1 and mca2 are directories,
when
(i) mca2 exists
mv command will exectecute and rename mca1 as mca2.

(ii) mca2 doesn‟t exist

AP15 Assuming that you are positioned in the directory /home/bvicam, what are these
commands presumed to do, and explain whether they will work at all:
(a) $ cd ../..
It changes the current directory to two steps before.
(b) $ mkdir ../bin
The mkdir command creates one or more new directories specified by the Directory parameter. Each new directory
contains the standard entries . (dot) and .. (dot-dot). 

(c) $ rmdir ..
The rmdir command removes the directory, specified by the Directory parameter, from the system. The directory
must be empty before you can remove it, and you must have write permission in its parent directory.

(d) $ ls ..
The ls command writes to standard output the contents of each specified Directory parameter or the name of each
specified  File parameter, along with any other information you ask for with the flags. 
BP1 Apply Peterson algorithm for solving the critical section problem with C
programming or Java multi-threaded programming. Assume appropriate code snippet
for critical section.

Solution:
class peterson {
static boolean[] flag = {false,
false}; static int turn = 0;
static int N = 4;
static Thread process(int i) {
return new Thread(() ->
{ int j = 1 - i;
for (int n=0; n<N; n++)
{ log(i+": want CS"); //
LOCK flag[i] = true; // 1
turn = j; // 2
while (flag[j] && turn == j)
Thread.yield(); //
3 log(i+": in CS"+n);
sleep(1000 * Math.random()); //
4 log(i+": done CS"); // UNLOCK
flag[i] = false; // 5
}
});
}

public static void main(String[] args)


{ try {
log("Starting 2 processes (threads)
..."); Thread p0 = process(0);
Thread p1 = process(1);
p0.start();
p1.start();
p0.join();
p1.join();
}
}
static void sleep(double t)
{ try { Thread.sleep((long)t);
}
catch (InterruptedException e) {}
}
static void log(String x)
{ System.out.println(x);
}
}

Output:
BP2: Apply Bakery algorithm for synchronization of processes/threads in a C or Java
program. Assume appropriate code snippet for critical
section.

public class bakery extends Thread {


// Variables for the threads.
public int thread_id; // The id of the current thread.
public static final int countToThis = 200;
public static final int numberOfThreads = 5;
public static volatile int count = 0; // A simple counter for the testing.
// Global variables for the bakery's algorithm.
private static volatile boolean[] choosing = new boolean[numberOfThreads];

private static volatile int[] ticket = new int[numberOfThreads];


/*
* Thread constructor.
*/
public bakery(int id) {
thread_id = id;
}
// Simple test of a global counter.
public void run() {
int scale = 2;
for (int i = 0; i < countToThis; i++) {
lock(thread_id);
// Start of critical section.
count = count + 1;
System.out.println("I am " + thread_id + " and count is: "

+ count);

try {
sleep((int) (Math.random() * scale));
} catch (InterruptedException e) { /* nothing */ }
// End of critical section.
unlock(thread_id);
} // for
} // run method
/*
* Method that does the lock of the bakery's algorithm.
*/
public void lock(int id) {

choosing[id] = true;
// Find the max value and add 1 to get the next available ticket.
choosing[id] = false;
// System.out.println("Thread " + id + " got ticket in Lock");
for (int j = 0; j < numberOfThreads; j++) {
// If the thread j is the current thread go the next
thread. if (j == id)
continue;
// Wait if thread j is choosing right
now. while (choosing[j]) { /* nothing */ }

while (ticket[j] != 0 && (ticket[id] > ticket[j] || (ticket[id] ==

ticket[j] && id > j))) { /* nothing */ }

} // for
}
/*
* Method that leaves the lock.
*/
private void unlock(int id) {
ticket[id] = 0;
// System.out.println("Thread " + id + " unlock");
}
/*
* Method that finds the max value inside the ticket array.
*/
private int findMax() {
int m = ticket[0];
for (int i = 1; i < ticket.length; i++)
{ if (ticket[i] > m)
m = ticket[i];

}
return m;
}
public static void main(String[] args) {
// Initialization of the global variables (it is not necessary at all).
for (int i = 0; i < numberOfThreads; i++) {
choosing[i] = false;
ticket[i] = 0;
}
bakery[] threads = new bakery[numberOfThreads]; // Array of threads.
// Initialize the threads.
for (int i = 0; i < threads.length; i++) {
threads[i] = new bakery(i);
threads[i].start();
}
// Wait all threads to finish.
for (int i = 0; i < threads.length; i++)
{ try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\nCount is: " + count);
System.out.println("\nExpected was: " + (countToThis
*

numberOfThreads));
}
}
Output:
BP3: Write C or Java program to simulate and solve the Producer-Consumer problem

Solution:
import java.util.LinkedList;

public class ProducerConsumer {


public static void main(String[] args)
throws InterruptedException{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{ try
{ pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both
threads t1.start();
t2.start();
// t1 finishes before
t2 t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws
InterruptedException{ int value = 0;
while (true) {
synchronized (this)
{
while (list.size() == capacity)
wait();
System.out.println("Producer produced-" + value);
// to insert the jobs in the list
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
notify();
Thread.sleep(1000);
}
}
}
}
}
Output:
BP4: Implement Semaphore(s) in a C or Java-multithreaded program to simulate the
working and solution of Reader-Writer problem. Assume multiple readers and writers.

Solution:
import java.util.concurrent.*;
//A shared resource/class.
class Shared
{
static int count = 0;
}
class MyThread extends Thread
{
Semaphore sem;
String threadName;
public MyThread(Semaphore sem, String threadName)
{
super(threadName);
this.sem = sem;
this.threadName = threadName;
}
@Override
public void run() {
// run by thread A
if(this.getName().equals("A"))
{
System.out.println("Starting " + threadName);
try
{
// First, get a permit.
System.out.println(threadName + " is waiting for a permit.");
// acquiring the
lock sem.acquire();
System.out.println(threadName + " gets a permit.");
for(int i=0; i < 5; i++)
{
Shared.count++;
System.out.println(threadName + ": " + Shared.count);
// Now, allowing a context switch -- if possible.
// for thread B to execute
Thread.sleep(10);
}
} catch (InterruptedException exc)
{ System.out.println(exc);
}
// Release the permit.
System.out.println(threadName + " releases the permit.");
sem.release();
// run by thread B
else
{
System.out.println("Starting " + threadName);
try
{
// First, get a permit.
System.out.println(threadName + " is waiting for a permit.");
// acquiring the
lock sem.acquire();
System.out.println(threadName + " gets a permit.");
// Now, accessing the shared resource.
// other waiting threads will wait, until this
// thread release the lock
for(int i=0; i < 5; i++)
{
Shared.count--;
System.out.println(threadName + ": " + Shared.count);
// Now, allowing a context switch -- if possible.
// for thread A to execute
Thread.sleep(10);
}
} catch (InterruptedException exc)
{ System.out.println(exc);
}
// Release the permit.
System.out.println(threadName + " releases the permit.");
sem.release();
}
}
}
// Driver class
public class SemaphoreDemo
{
public static void main(String args[]) throws InterruptedException
{
// creating a Semaphore object
// with number of permits 1
Semaphore sem = new Semaphore(1);
// creating two threads with name A and B
// Note that thread A will increment the count
// and thread B will decrement the count
MyThread t1 = new MyThread(sem, "A");
MyThread t2 = new MyThread(sem, "B");
// stating threads A and B
t1.start();
t2.start();
// waiting for threads A and B
t1.join();
System.out.println("count: " + Shared.count);
}
}

Output:
BP5: Create a zombie process and an orphan process in a „C‟ program with appropriate
system calls.

Solution:
=>Zombie process

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
int main()
{
// Fork returns process id
// in parent process
pid_t child_pid = fork();
// Parent process
if (child_pid > 0)
sleep(50);
// Child process
else
exit(0);
printf("Woke up after 50
seconds..."); return 0;
}

Output:
=>Orphan process

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Create a child process
int pid = fork();
if (pid > 0)
printf("in parent process");
// Note that pid is 0 in child process
// and negative if fork() fails
else if (pid == 0)
{
sleep(30);
printf("in child process");
}
return 0;
}

Output:
BP6: Write a „C‟ program which creates a new process and allows both, child and parent,
to report their identification numbers (ids). The parent process should wait for the
termination of the child process.

Solution:
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf("\nI'mInChild..");
printf("\nChild Process Id:%d",getpid()); printf("\
nChildClosed");
exit(0);
}
else
{
wait(NULL);
printf("\nFrom Parent Process..");
printf("\nParent Process Id: %d",getpid());
printf("\nParent's Child Id: %d",pid);
printf("\nParentClosed");
}
printf("\n");
return 0;
}
Output:

BP7: Write two „C‟ programs (A.c and B.c) where one program (A.c) creates a child
process and then that child process executes the code of other program (B.c). The logic of
program „B.c‟ is to generate all the prime numbers within the specified limit.

Solution:
=>A.c
#include<stdio>
#include<unistd>
int main(){
printf("I am executing A.c \n");
printf("PID of A.c is %d\n",getpid());
char *args[]={"./B.c",NULL};
execv(args[0],args);
}
=>B.c

#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
void main()
{
int n;
printf("\nUp to How Many Numbers:");
scanf("%d",&n);
{
int flag=0;
for(int j=2; j<=i/2; j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(i==1)
{
printf("\n1 is neither Prime nor Composite..\n");
}
else
{
if(flag==0)
{
printf("%d is a Prime Number..\n",i);
}
}
}
}

Output:
BP8: Write an appropriate „C‟ program which implements the concept of dynamic
memory allocation (use of malloc(), calloc(), realloc(), and free() system call).

Solution:
=> Demonstration of malloc()

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void main()
{
int n, *ptr, i;
printf("Input array size: ");
scanf("%d",&n);
ptr = (int *)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("\nNo Allocation of memory");
}
else
{
printf("\nMemory Allocation Done!"); printf("\
nAddress of first byte = %p", ptr); for(i=0; i<n;
i++)
{
ptr[i] = i+10;
}
}
printf("\nArray Elements: \n");
for(i=0; i<n; i++)
{
printf("%d ", ptr[i]);

// printf("%p ", ptr+i);


}
=>Demonstration of calloc()

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
return 0;
}

Output:

=> Demonstration of realloc()

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nThe new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}

Output:
=> Demonstration of free()

#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
n = 5;

printf("Number of elements: %d\n", n);


// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL)
{ printf("Memory not allocated.\
n"); exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated printf("\
nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
}

Output:

BP9: Create a text file, named as „courses.txt‟ that contains the following four lines:
Java Programming
Operating System
Discrete Structure
Write a „C‟ program that forks three other processes. After forking, the parent process
goes into wait state and waits for the children to finish their execution. Each child process
reads a line from the „course.txt‟ file (Child 1 Reads Line 1, Child 2 Reads Line 2, and
Child 3 Reads Line 3) and each prints the respective line. The lines can be printed in any
order.

Solution:
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<stdio.h>
void main()
{
pid_t pid;
int fd;
int linecount[3]={16,17,21};
int startpoint[3]={0,17,33};
for(int i=0;i<3;i++)
{
pid=fork();
if(pid==0)
{
char read_value[linecount[i]];
fd=open("course.txt",O_RDWR);
lseek(fd,startpoint[i],SEEK_SET);
read(fd, read_value,linecount[i]);
printf("%s\n",read_value);
close(fd);
exit(0);
}
else
{
wait(NULL);
}
}
}

Output:
CP1: Write a „C‟ program (using appropriate system calls of Linux) that generates „n‟
integers and stores them in a text file, named as „All.txt‟. Then, retrieve the stored
integers from this file and copy to “Odd.txt” and „Even.txt‟ based upon the type of
number, i.e. if the retrieved integer if odd number then store in „Odd.txt‟ file or if the
retrieved integer is even then store in „Even.txt‟ file. Finally, display the contents of all
three files on the screen

Solution:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
void main()
{
int n;
printf("\nUp to How Many Numbers: ");
scanf("%d",&n);
char write_value[n], read_value[n];
int fd,fd_odd,fd_even; printf("\
nWriting To All.txt: "); for(int
i=0;i<n;i++)
{
write_value[i]=(i+1)+'0';
printf("%c",write_value[i]);
}
printf("\n");
fd=open("All.txt",O_CREAT | O_WRONLY, 0777);
write(fd,write_value,n);
close(fd);
fd=open("All.txt", O_RDWR);
read(fd,read_value,n);
char write_odd[n/2],write_even[n/2];
int ind_odd=0,ind_even=0;
for(int i=0;i<n;i++)
{
int temp=read_value[i]; if(temp
%2==0)
{
write_even[ind_even++]=read_value[i];
}
else
{
write_odd[ind_odd++]=read_value[i];
}
}
printf("\nWriting To odd.txt:");
for(int j=0;j<n/2;j++)
{
printf("%c",write_odd[j]);
}
printf("\n");
printf("\nWriting To even.txt:");
for(int j=0;j<n/2;j++)
{
printf("%c",write_even[j]);
}
printf("\n");
fd_odd=open("odd.txt",O_CREAT | O_RDWR, 0777);
write(fd_odd, write_odd, n/2); close(fd_odd);
fd_even=open("even.txt",O_CREAT | O_RDWR, 0777);
write(fd_even, write_even, n/2); close(fd_even);
}

Output:
CP2: Write a program in „C‟ which accepts the file or directory name and permission
(access rights) from the user and then changes the access rights accordingly. Use
appropriate system call(s) of Linux.

Solution:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>

int main(){
int inp,check,fd; unsigned int perm; char name[51] = "";
printf("Select\n1.Create Directory\n2.Create File\n");
scanf("%d", &inp);
printf("Enter permission: ");
scanf("%o", &perm);
switch(inp)
{
case 1: printf("Enter dir name:
"); scanf("%50s", name);
check = mkdir(name, perm);
if (!check)
{
printf("Directory created\n");
}
else
{
printf("Unable to create directory\n");
}
break;
case 2: printf("Enter file name:
"); scanf("%50s", name);
fd = open(name,O_CREAT | O_RDWR, perm);
printf("File created\n");
close(fd);
break;
Output:

CP3: Write a „C‟ program (using appropriate system calls of Linux) which generates and
stores the characters from „a‟ to „z‟. Then, display the stored
characters in alternative manner, like: a, c, e, g, ..., etc.

Solution:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
void main()
{
int n=26,ind=0;
int fd,sizeRead,sizeWrite;
char write_value[n], read_value[n];
for(int i=65;i<91;i++)
{
write_value[ind]=i;
ind++;
sizeWrite=write(fd, write_value,n);
close(fd);
fd=open("alpha.txt",O_RDWR);
sizeRead=read(fd,read_value,n);
close(fd);
for(int i=0;i<n;i+=2)
{
printf("%c",read_value[i]);
}
printf("\n");
}

Output:

CP4: Write a „C‟ program (using appropriate system calls of Linux) which receives roll
number and names of „n‟ students, from the user one-by-one and then stores them in a
text file, named as „Student.txt‟. After inserting all „n‟ roll numbers and names, display
the contents of file. Also, display the access rights of the file „Student.txt‟.

Solution:
#include <stdio.h>
#include <stdlib.h>

struct student {
int rollno; char
name[200];
};

int writef(FILE *file, struct student *s)


{ int out = fprintf(
file, "%d\n%s\
n",
s->rollno, s->name
);
fflush(file); Operating System with Linux (MCA-167) Practical
File
return out;
}

int readf(FILE *file, struct student *s) {


if (fscanf(file, "%d", &s->rollno) == EOF) return 0;
if (fscanf(file, "%s", s->name) == EOF) return 0;
return 1;
}

int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);

struct student s;
FILE *file = fopen("Student.txt", "w");
for (int i = 0; i < n; i++) {
printf("Enter the roll no of student %d: ", i);
scanf("%d", &s.rollno);
printf("Enter the name of student %d: ", i);
scanf("%s", s.name);
writef(file, &s);
}
fclose(file);

file = fopen("Student.txt", "r");


int i = 0;
while (readf(file, &s)) {
printf("Student #%d: %s\n", s.rollno, s.name);
if(i == 5) break;
i++;
}
fclose(file);

return 0;
}

Output:
Operating System with Linux (MCA-167) Practical File

CP5 Demonstrate the use of following system calls by writing an appropriate „C‟
program.
(a) lseek()
(b) chmod()
(c) umask()
(d) access()
(e) utime()

Solution:
1. 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

=> Iseek()

#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int fd;
char buffer[80];
char msg[50]="hello i am using linux";
fd=open("check.txt",O_RDWR);
printf("fd=%d",fd); if(fd!=-1)
{
printf("\ncheck.txt opened wih read write access\n");
write(fd,msg,sizeof(msg));
lseek(fd,0,SEEK_SET);
read(fd,buffer,sizeof(msg));
close(fd);
}
return 0;
}

Output:

2. chmod: In Unix-like operating systems, the chmod command is used to change the
access mode of a file. The name is an abbreviation of change mode.
Syntax : chmod [reference][operator][mode] file...
The references are used to distinguish the users to whom the permissions apply i.e. they
are list of letters that specifies whom to give permissions. The references are represented
by one or more of the following letters: Reference Class Description u owner file's owner
g group users who are members of the file's group

=> chmod()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
int main(int argc,char **argv)
{
char mode[]="0777";
char buf[100]="/home/vis/os";
int i;
i=strtol(mode,0,8);
if(chmod(buf,i)<0)
{
fprintf(stderr,"%s:error in chmod(%s,%s)-%d(%s)\n",
exit(1);
}
return(0);
}

Output:

umask() : On Linux and other Unix-like operating systems, new files are created with a
default set of permissions. Specifically, a new file's permissions may be restricted in a
specific way by applying a permissions "mask" called the umask. The umask command is
used to set this mask, or to show you its current value.
=>mask()

#define _POSIX_SOURCE
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main(){
int fd;
mode_t old;
printf("Old mask in: %i\n",
old=umask(S_IRWXG)); if((fd = creat("new.txt",
S_IRWXU|S_IRWXG)) < 0){ perror("creat()
error");
}
else{
system("ls -l new.txt");
close(fd);
unlink("new.txt");
}
umask(old);
}
=>access()

#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
extern int errno;

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


{
int fd=access("course.txt",F_OK);
if(fd==-1)
{
printf("Error Number:%d\n",errno);
perror("Error Description:");
}
else
printf("No error\n");
return 0;
}

Output:

=> utime()

#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main(void)
{
FILE* uptimefile;
char uptime_chr[28];
long uptime=0;
if((uptimefile=fopen("/proc/uptime","r"))==NULL)
perror("supt"),exit(EXIT_FAILURE);
fgets(uptime_chr, 12, uptimefile);
fclose(uptimefile);
uptime=strtol(uptime_chr,NULL,10);
printf("System up for %ld seconds,%ld hours \n",uptime,uptime/ 3600);
exit(EXIT_SUCCESS);
}

Output:

You might also like