LAB – I
Pre-lab:
Whatis command is helpful to get brief information about Linux commands or functions. Whatis
command displays man page single line description for command that matches string passed as
a command line argument to whatis command. man command, short for manual, provides help
for the commands, utilities or function in Linux and Unix systems. If you are new to Unix and
Linux system and looking for help command in Unix or info command in Linux to get started,
man command is the answer.
os@klu:~$ whatis ls
ls (1) - list directory contents
os@klu:~$ whatis ln
ln (1) - make links between files
os@klu:~$ whatis rm
rm (1) - remove files or directories
os@klu:~$ whatis mv
mv (1) - move (rename) files
os@klu:~$ whatis cp
cp (1) - copy files and directories
os@klu:~$ whatis df
df (1) - report file system disk space usage
os@klu:~$ whatis du
du (1) - estimate file space usage
os@klu:~$ whatis ps
ps (1) - report a snapshot of the current processes.
Pre-lab:
2. Write a C program that reads line by line in myfile.txt and prints the first 10-digit number in the
given file (digits should be continuous), If not found then print first 10 characters excluding
numbers.
/*
Write a C program that reads line by line in myfile.txt and prints the first 10-digit
number in the given file (digits should be continuous), If not found then print first 10
*/
#include <stdio.h>
int main()
int count;
int c=0;
while(1)
count = 0;
for(int i=0;i<10;i++){
c = getc(fp);
if( c == -1)
break;
count++;
}
if(c == -1)
break;
if(count==10){
char s[10];
fseek(fp,-10,SEEK_CUR);
fgets(s,11,fp);
printf("%s",s);
break;
fseek(fp,-9,SEEK_CUR);
if (count!=10)
rewind(fp);
for(int i=0;i<10;)
c = getc(fp);
continue;
printf("%c",c);
i++;
return 0;
}
3. Write a C program that saves 10 random numbers to a file, using own “rand.h” header file which
contains your own random( ) function.
rand.h
#include <stdlib.h>
int ownrand(){
return rand()%10;
main.c
#include <stdio.h>
#include <time.h>
#include "rand.h"
int main()
srand(time(0));
FILE *fptr;
fptr = fopen("random.txt","w");
fprintf(fptr, "\n");
return 0;
}
In-lab:
2. As part of the tradition, Treasure Hunt is played in Hogwarts school of witchcraft and wizardry by
all the houses. By decoding all the hints, Gryffindor has reached the final level, the rest were
knocked out. Gryffindors have obtained the Treasure, to unlock the treasure they must perform the
following operations using UNIX system calls (open, close, read, write): a) Open and Read the file
/etc/passwd, write all the contents of file to crypt.txt (In pwd).
b) Close the file (/etc/passwd).
c) Using lseek go to the last line of crypt.txt.
d) Store the first 12 characters of last line to a file decrypt.txt
e) Display the contents of decrypt.txt
As part of the tradition, Treasure Hunt is played in Hogwarts school of witchcraft and
wizardry by all the houses. By decoding all the hints, Gryffindor has reached the final
level, the rest were knocked out. Gryffindors have obtained the Treasure, to unlock
the treasure they must perform the following operations using UNIX system calls
a) Open and Read the file /etc/passwd, write all the contents of file to crypt.txt
(In pwd).
*/
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
int main(){
char buf;
int c;
// Creating crypt.txt
while(1){
if(read(fd1,&buf,1)!=0)
write(fd2,&buf,1);
else
break;
close(fd1);
close(fd2);
fd1 = open("crypt.txt",O_RDONLY);
// creating decrypt.txt
lseek(fd1,-2,SEEK_END);
read(fd1,&buf,1);
printf("%c",buf);
while(buf != '\n'){
lseek(fd1,-2,SEEK_CUR);
read(fd1,&buf,1);
}
//saving the 12 characters to decrypt.txt
char s[12];
read(fd1,s,12);
write(fd2,s,12);
close(fd1);
close(fd2);
while(1){
if(read(fd1,&buf,1)!=0)
write(1,&buf,1);
else
break;
return 0;
3. Write a UNIX system program that will perform copy data from one file to other file with error
handling. Both file names to the program should be given as command line arguments.
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <stdio.h>
#include<stdlib.h>
char buf;
int sourcefile,destfile,n;
if(argc!=3)
exit(1);
else
sourcefile=open(argv[1],O_RDONLY);
if(sourcefile==-1)
exit(1);
else
if(destfile==-1)
exit(1);
else
n=read(sourcefile,&buf,1);
while(n != 0 && n != -1 )
n=read(sourcefile,&buf,1);
}
close(sourcefile);
close(destfile);
return 0;
}
Post-lab:
1) Write a UNIX system program that creates a file with a hole in it.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
int fd;
perror("creat error");
/* offset now = 10 */
perror("lseek error");
exit(0);
}
/*
$ ./a.out
$ ls -l file.hole
$ od -c file.hole
Both files are the same size, the file without holes consumes 20 disk blocks,
*/
2) Write a program using system calls to write in reverse order of all the contents of file
(/etc/passwd) to reverse.txt. Show a pictorial arrangement of File Descriptor, File and Inode tables
for a single process that has two different files open.
/*
Write a program using system calls to write in reverse order of all the contents of file
(/etc/passwd) to reverse.txt. Show a pictorial arrangement of File Descriptor, File and Inode
tables for a single process that has two different files open.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char buf;
perror("open");
exit(2);
while (lseek(fd, -2, SEEK_CUR) >= 0) { /* and then back by two bytes */
perror("read");
exit(1);
perror("write");
exit(1);
close(fd1);
3) Write a program using system calls to print the content of the file (/etc/passwd) onto the
console.
/*
Write a program using system calls to print the content of the file (/etc/passwd) onto the
console.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
perror("open");
exit(2);
perror("write");
exit(1);
}
LAB – III
Pre-lab:
2. The process obtains its own PID and its parent’s PID using the getpid and getppid system calls. The
program also prints the effective UID and GID, which normally are equal to the real UID and GID. Write a
UNIX system program that prints PID, PPID, real and effective UIDs and GIDs and fetches and sets PATH
/*
The process obtains its own PID and its parent’s PID using the getpid and getppid system
calls. The program also prints the effective UID and GID, which normally are equal to the
real UID and GID. Write a UNIX system program that prints PID, PPID, real and effective
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
pid_t p;
if(fork()==0){
char *s=strdup(getenv("PATH"));
setenv("PATH","sumanth",1);
printf("PATH : %s\n",getenv("PATH"));
setenv("PATH",s,1);
printf("PATH : %s\n",getenv("PATH"));
}
In-lab:
1. Minni has a document named "Mickey" which contains the verses of a song. She is interested to
know the count of words and lines of the song. She utilizes Linux directions and system calls, in
order to accomplish her objective. Help Minni to finish her assignment by utilizing fork system call.
The parent process tallies the no.of lines utilizing execvp() and the child procedure checks the
aggregate no.of words in the song. Display the check of words pursued by the tally of lines utilizing
wait(). Demonstrate the child’s various exit status. Show a pictorial arrangement - Sharing of open
files between parent and child after fork
#include <unistd.h>
#include <stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include<wait.h>
#include <fcntl.h>
int main()
switch(fork())
case -1:
perror("fork");
exit(1);
case 0:
//child
if(execvp("wc",ccomm)<0)
exit(2);
break;
default:
if(execvp("wc",pcomm)<0)
exit(3);
break;
2. Write a program to execute a given command and show the usage of dup2 function in a way that
instead of printing on monitor, redirecting the output to a file named "Lab3.txt"
/*
Write a program to execute a given command and show the usage of dup2 function in
a way that instead of printing on monitor, redirecting the output to a file named
"Lab3.txt"
*/
#include <unistd.h>
#include <stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include<wait.h>
#include <fcntl.h>
if(argc > 1 ){
if(fork()==0){
int fd = open("Lab3.txt",O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
dup2(fd,1);
perror("exec error");
exit(2);
else{
int rv;
wait(&rv);
exit(0);
else{
}
Post-lab:
1. Write a program redirection.c that achieves the effect of redirection without using the < and >
symbols. Child opens files and uses dup2 to reassign the descriptors and execute a command line.
Note: The first two arguments are input and output filenames. The command line to execute is
specified as the remaining arguments.
Redirection:
#include <unistd.h>
#include <stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <wait.h>
if (fork() == 0) { /* Child */
exit(1);
exit(1);
dup2(fd1,0);
dup2(fd2,1);
exit(2);
else { /* Parent */
wait(&rv);
exit(0);
2. Write a UNIX system program to create zombie (by letting parent sleep & child dies) and orphan
process (by letting child sleep for 2 minutes Parent doesn't call wait and dies immediately).
Zombie
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
// Parent process
if (pid > 0)
sleep(20);
// Child process
else
exit(0);
return 0;
2_2)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
if (pid > 0)
printf("Parent process\n");
printf("ID : %d\n\n",getpid());
else if (pid == 0)
printf("Child process\n");
// getpid() will return process id of child process
printf("ID: %d\n",getpid());
sleep(0);
printf("ID: %d\n",getpid());
else
return 0;
}
LAB – IV
Pre-lab:
1. Write a C program using spin() function to understand that loops and prints a certain string value.
And also run it with multiple instances (of the same program) to demonstrate virtualizing the CPU
use gettimeofday() library function.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
double GetTime() {
struct timeval t;
assert(rc == 0);
double t = GetTime();
if (argc != 2) {
exit(1);
}
while (1) {
printf("%s\n", str);
Spin(1);
return 0;
2. xv6 is a re-implementation of Dennis Ritchie's and Ken Thompson's Unix Version 6 (v6). xv6 loosely
follows the structure and style of v6, but is implemented for a modern x86-based multiprocessor using
ANSI C. Adding a system call in XV6 OS: Show you how to add a system call to XV6 OS. Add a simple
helloworld system call which will print hello world and the argument passed to the system call.
In-lab:
1) Zabih the Prime Minister of Honolulu is very strict regarding the taxation policy in his country. On the
very first day of his tenure as the Prime Minister he formed a committee of his council of ministers
belonging to different regions. This committee members followed by had a group of well talented tax
officers who would look out at the working of the tax department.
a) The Prime Minister got an anonymous tip that certain people in the administration were practicing
unethical means to evade taxes.
b) The Prime Minister ordered the Chief of Police to question all of them and find the culprit.
c) Now, in order to call all of them for questioning, one needs to know the addresses of all the workforce
working under the tax department.
d) Help the police department to gather the information regarding the addresses of the workforce.
e) Here, the council of ministers are a segment of the taxation norm and the officers working under
them can be considered as different variables for the tax department.
f) Write a UNIX system program to print all the addresses of all the segments and the addresses of the
variables residing in their respective segments.
#include <stdio.h>
#include <unistd.h>
int
printf("Text Locations:\n");
printf("\tAddress of main: %p\n", main);
printf("Stack Locations:\n");
afunc();
p = (char *) alloca(32);
if (p != NULL) {
printf("Data Locations:\n");
printf("BSS Locations:\n");
nb = sbrk((ptrdiff_t) 0);
printf("Heap Locations:\n");
nb = sbrk((ptrdiff_t) 0);
/* infinite loop */
while (1) {}
void
afunc(void)
return;
}
2) Lottery Sch
Post-lab:
1) Write a UNIX system program to establish a connection between two processes, in such a way
that output of one process is input of the other using the pipe() system call
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int n, fd[2];
char buf[100];
pipe(fd);
if (fork()) {
close(fd[1]);
else{
close(fd[0]);
}
2) Write a system program to demonstrate shared memory IPC - execute with and without
command line arguments.
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
key_t key;
int shmid;
char *data;
if (argc > 2) {
exit(1);
perror("ftok");
exit(1);
perror("shmget");
exit(1);
printf("SHMID = %d\n",shmid);
perror("shmat");
exit(1);
if (argc == 2) {
} else
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
Review 1:
LAB – V
Pre-lab:
2)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
char *ptr[MAX_ALLOCS];
printf("\n");
exit(5); }
exit(5); }
exit(5); }
ptr[j] = malloc(blockSize);
if (ptr[j] == NULL)
{ perror("malloc");
exit(5); }
free(ptr[j]);
exit(10);
}
In-lab:
1) Twin Sisters Riya and Siya collected money to help their friend Radha to buy books. Riya
approached her elder sister Diya to help her calculate the total amount she collected. Riya said that
she collected money from ‘n’ persons and gave Diya a list of values of amount she collected from
each person. After a while Siya arrived and said that she also collected money from ‘m’ people and
submitted information like Riya.
Now Diya has inputs as bellow
First value is ‘n’, followed by n values of amounts collected by Riya. Then the next value is ‘m’,
followed by m values of amounts collected by Siya.
As you are explaining Diya, how to allocate memory dynamically. Take this situation and provide her
with an example program, which stores the above n values provide by Riya in an array using malloc
() and then m values provided by Siya in the same array and using realloc() calculate the total
amount they have collected using malloc(), realloc(). Don’t forget to free the memory allocated, by
using free ().
2) One of the simplest methods for memory allocation is to divide memory into several fixed-sized
partitions. Each partition may contain exactly one process. In this multiple-partition method, when
a partition is free, a process is selected from the input queue and is loaded into the free partition.
When the process terminates, the partition becomes available for another process. The operating
system keeps a table indicating which parts of memory are available and which are occupied.
Finally, when a process arrives and needs memory, a memory section large enough for this process
is provided. When it is time to load or swap a process into main memory, and if there is more than
one free block of memory of enough size, then the operating system must decide which free block
to allocate. Best-fit strategy chooses the block that is closest in size to the request. First-fit chooses
the first available block that is large enough. Worst-fit chooses the largest available block.
Post-lab:
Write a simple memory allocator: memalloc is a simple memory allocator. Which uses own malloc (),
calloc(), realloc() and free() implemented using system calls.
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
struct header_t {
size_t size;
unsigned is_free;
};
pthread_mutex_t global_malloc_lock;
while(curr) {
return curr;
curr = curr->next;
return NULL;
}
void *programbreak;
if (!block)
return;
pthread_mutex_lock(&global_malloc_lock);
programbreak = sbrk(0);
/*
heap and release memory to OS. Else, we will keep the block
*/
if (head == tail) {
} else {
tmp = head;
while (tmp) {
if(tmp->next == tail) {
tmp->next = NULL;
tail = tmp;
tmp = tmp->next;
/*
*/
*/
pthread_mutex_unlock(&global_malloc_lock);
return;
header->is_free = 1;
pthread_mutex_unlock(&global_malloc_lock);
size_t total_size;
void *block;
return NULL;
pthread_mutex_lock(&global_malloc_lock);
header = get_free_block(size);
if (header) {
header->is_free = 0;
pthread_mutex_unlock(&global_malloc_lock);
/* We need to get memory to fit in the requested block and header from OS. */
block = sbrk(total_size);
pthread_mutex_unlock(&global_malloc_lock);
return NULL;
header = block;
header->size = size;
header->is_free = 0;
header->next = NULL;
if (!head)
head = header;
if (tail)
tail->next = header;
tail = header;
pthread_mutex_unlock(&global_malloc_lock);
}
void *calloc(size_t num, size_t nsize)
size_t size;
void *block;
if (!num || !nsize)
return NULL;
return NULL;
block = malloc(size);
if (!block)
return NULL;
memset(block, 0, size);
return block;
void *ret;
if (!block || !size)
return malloc(size);
return block;
ret = malloc(size);
if (ret) {
/* Relocate contents to the new bigger block */
free(block);
return ret;
void print_mem_list()
while(curr) {
curr = curr->next;
/*
The -fPIC and -shared options makes sure the compiled output has position-independent code and tells
the linker to produce a shared object suitable for dynamic linking.
On Linux, if you set the enivornment variable LD_PRELOAD to the path of a shared object, that file will
be loaded before any other library. We could use this trick to load our compiled library file first, so that
the later commands run in the shell will use our malloc(), free(), calloc() and realloc().
ls
memalloc.c memalloc.so
You can also run your own programs with this memory allocator.
*/
/*
vishnu@mannava:~$ cc sll.c
*/
/*
vishnu@mannava:~$ cc sll.c
vishnu@mannava:~$./a.out
543210
54310
*/
#include <stdlib.h>
struct node
int data ;
};
node *temp;
if(head->data == num)
temp = head->next;
free(head);
head = temp;
else {
while(head->next->data != num)
head = head->next;
temp = head->next->next;
free(head->next);
head->next = temp;
void main( )
int i;
head->data = 0;
head->next = NULL;
printf ( "\n insert 5 more elements in to Linked List - Already element 0 is in SLL" ) ;
tmp = malloc(sizeof(node));
if(tmp == NULL)
printf("malloc failed");
tmp->data = i;
tmp->next = head;
head = tmp;
while(tmp != NULL) {
deletenode(head,2);
while(tmp != NULL) {
}
LAB – VI
Pre-lab:
In-lab:
Post-lab:
Review 2:
LAB – VII
Pre-lab:
3)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
int main()
pthread_t thread_one[5];
int i=0;
int a[5];
for(i=0;i<5;i++){
a[i]=i;
for(i=0;i<5;i++)
pthread_join(thread_one[i], NULL);
// wait for thread two
printf("done\n");
}
In-lab:
1)
#include <pthread.h>
#include<semaphore.h>
#include<stdio.h>
sem_t sem1;
int loc, j;
sem_wait(&sem1);
loc = glob;
loc++;
glob = loc;
sem_post(&sem1);
return NULL;
int
long loops, s;
sem_init(&sem1,0,1);
if (s != 0)
perror("pthread_create");
s = pthread_create(&t2, NULL, threadFunc, &loops);
if (s != 0)
perror("pthread_create");
s = pthread_join(t1, NULL);
if (s != 0)
perror("pthread_join");
s = pthread_join(t2, NULL);
if (s != 0)
perror("pthread_join");
exit(0);
2)
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#define no_threads 10
#define n 20
long a[n];
long rank=(long*)st;
long my_n=n/no_threads;
long i;
pthread_mutex_lock(&mtx);
pthread_mutex_unlock(&mtx);
return NULL; }
main()
long i;
pthread_t thread[10];
a[i] = i+1;
if (pthread_join(thread[i], NULL) != 0)
exit(0); }
Post-lab:
1)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#define NBUFF 10
struct {
int buff[NBUFF];
sem_t *mutex;
sem_t *nempty;
sem_t *nstored;
} shared;
pthread_t
tid_produce, tid_consume;
if (argc != 2)
nitems = atoi(argv[1]);
Synchronization - II
pthread_setconcurrency(2);
pthread_join(tid_produce, NULL);
pthread_join(tid_consume, NULL);
sem_unlink(SEM_MUTEX);
sem_unlink(SEM_NEMPTY);
sem_unlink(SEM_NSTORED);
exit(0);
/* end main */
/* include prodcons */
int i;
sem_wait(shared.nempty);
shared.buff[i % NBUFF] = i;
sem_post(shared.mutex);
sem_post(shared.nstored);
return(NULL);
int i;
sem_wait(shared.nstored);
sem_wait(shared.mutex);
if (shared.buff[i % NBUFF] == i)
sem_post(shared.mutex);
sem_post(shared.nempty);
return(NULL);
}
LAB – VIII
Pre-lab:
4)
#include<pthread.h>
#include<stdio.h>
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void thr_exit() {
Pthread_mutex_lock(&m);
done = 1;
Pthread_cond_signal(&c);
Pthread_mutex_unlock(&m);
printf("child\n");
thr_exit();
return NULL;
void thr_join() {
Pthread_mutex_lock(&m);
while (done == 0)
Pthread_cond_wait(&c, &m);
Pthread_mutex_unlock(&m);
printf("parent: begin\n");
pthread_t p;
thr_join();
printf("parent: end\n");
return 0;
}
In-lab:
1)
Post-lab:
1)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/types.h>
int nitems;
int buff[MAXNITEMS];
struct {
pthread_mutex_t mutex;
} put = { PTHREAD_MUTEX_INITIALIZER };
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
/* end globals */
void
/* include main */
if (argc != 3)
nitems = atoi(argv[1]);
nthreads = atoi(argv[2]);
pthread_setconcurrency(nthreads + 1);
count[i] = 0;
pthread_join(tid_produce[i], NULL);
pthread_join(tid_consume, NULL);
exit(0);
/* end main */
/* include prodcons */
for ( ; ; ) {
pthread_mutex_lock(&put.mutex);
pthread_mutex_unlock(&put.mutex);
return(NULL);
buff[put.nput] = put.nval;
put.nput++;
put.nval++;
pthread_mutex_unlock(&put.mutex);
pthread_mutex_lock(&nready.mutex);
if (nready.nready == 0)
pthread_cond_signal(&nready.cond);
nready.nready++;
pthread_mutex_unlock(&nready.mutex);
*((int *) arg) += 1;
int i;
pthread_mutex_lock(&nready.mutex);
while (nready.nready == 0)
pthread_cond_wait(&nready.cond, &nready.mutex);
nready.nready--;
pthread_mutex_unlock(&nready.mutex);
if (buff[i] == i)
return(NULL);
}
Review 3:
LAB – IX
Pre-lab:
In-lab:
Post-lab:
LAB – X
Pre-lab:
In-lab:
Post-lab:
Review 4:
Review 5:
LAB – XI
Pre-lab:
In-lab:
Post-lab:
Review 6:
LAB – XII
Pre-lab:
In-lab:
Post-lab: